DEV Community

Cover image for # Creating a Token Faucet on Stellar: A Beginner's Tutorial 🚰💧
cauhlins
cauhlins

Posted on

# Creating a Token Faucet on Stellar: A Beginner's Tutorial 🚰💧

Welcome, future Stellar developers! Today, we're going to embark on an exciting journey to create a Token Faucet on the Stellar network. Buckle up, because by the end of this tutorial, you'll be making it rain digital tokens! 🌧️💰

Table of Contents

  1. Introduction: What's a Token Faucet?
  2. Setting Up Your Stellar Development Environment
  3. Creating Our Cosmic Token
  4. Building the Faucet Smart Contract
  5. Deploying to the Stellar Testnet
  6. Creating a Web Interface
  7. Testing Our Faucet
  8. Conclusion and Next Steps

Introduction: What's a Token Faucet? 🤔

Imagine a magical water fountain that, instead of water, dispenses digital tokens. That's essentially what a token faucet is! It's a smart contract that gives out a small number of tokens to anyone who asks. Token faucets are commonly used on test networks to distribute tokens for testing purposes.

In our case, we'll be creating a faucet for "Cosmic Tokens" (CSM) – because who doesn't want tokens from outer space? 🌠

Setting Up Your Stellar Development Environment 🛠️

Before we dive into the code, let's set up our development environment. We'll be using Soroban, Stellar's smart contract platform.

  1. Install Rust and Cargo:
   curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
Enter fullscreen mode Exit fullscreen mode
  1. Install the Soroban CLI:
   cargo install --locked --version 20.0.0-rc2 soroban-cli
Enter fullscreen mode Exit fullscreen mode
  1. Set up a new Soroban project:
   soroban contract init cosmic-faucet
   cd cosmic-faucet
Enter fullscreen mode Exit fullscreen mode

Great job! You're now ready to create some stellar smart contracts! 🌟

Creating Our Cosmic Token

Before we can make our faucet, we need to create the token it will dispense. Let's create a simple Cosmic Token (CSM).

Edit your src/lib.rs file:

#![no_std]
use soroban_sdk::{contractimpl, symbol_short, token, Address, Env, Symbol};

#[derive(Clone)]
pub struct CosmicToken;

#[contractimpl]
impl CosmicToken {
    pub fn initialize(env: Env, admin: Address) -> Self {
        let token = token::Interface::new(&env, &env.current_contract_address());
        token.initialize(&admin, &7, &"Cosmic Token", &"CSM");
        Self
    }

    pub fn balance(env: Env, id: Address) -> i128 {
        let token = token::Interface::new(&env, &env.current_contract_address());
        token.balance(&id)
    }

    pub fn transfer(env: Env, from: Address, to: Address, amount: i128) {
        let token = token::Interface::new(&env, &env.current_contract_address());
        token.transfer(&from, &to, &amount);
    }
}
Enter fullscreen mode Exit fullscreen mode

This code creates a basic token with initialize, balance, and transfer functions. It's like creating your own cosmic currency! 🌌💰

Building the Faucet Smart Contract 🚰

Now, let's create our faucet contract. Create a new file src/faucet.rs:

#![no_std]
use soroban_sdk::{contractimpl, token, Address, Env};

const FAUCET_AMOUNT: i128 = 100; // Amount of tokens to dispense
const COOLDOWN_PERIOD: u64 = 86400; // 24 hours in seconds

#[derive(Clone)]
pub struct CosmicFaucet;

#[contractimpl]
impl CosmicFaucet {
    pub fn initialize(env: Env, token: Address) -> Self {
        env.storage().set(&Symbol::short("token"), &token);
        Self
    }

    pub fn drip(env: Env, to: Address) -> i128 {
        let token: Address = env.storage().get(&Symbol::short("token")).unwrap();
        let token_client = token::Client::new(&env, &token);

        // Check if user is on cooldown
        let last_drip: u64 = env.storage().get(&to).unwrap_or(0);
        let current_time = env.ledger().timestamp();
        if current_time - last_drip < COOLDOWN_PERIOD {
            panic!("You're still on cooldown! Try again later.");
        }

        // Update last drip time
        env.storage().set(&to, &current_time);

        // Transfer tokens
        token_client.transfer(&env.current_contract_address(), &to, &FAUCET_AMOUNT);
        FAUCET_AMOUNT
    }
}
Enter fullscreen mode Exit fullscreen mode

This faucet dispenses 100 Cosmic Tokens to each user, with a 24-hour cooldown period. It's like a cosmic vending machine that refills daily! 🎰🌠

Deploying to the Stellar Testnet 🚀

Time to launch our cosmic creation into the Stellar testnet!

  1. Build your contracts:
   soroban contract build
Enter fullscreen mode Exit fullscreen mode
  1. Create a Stellar account:
   soroban config identity generate alice
Enter fullscreen mode Exit fullscreen mode
  1. Fund your account on the testnet:
   soroban config network add testnet --rpc-url https://soroban-testnet.stellar.org
   soroban config identity fund alice --network testnet
Enter fullscreen mode Exit fullscreen mode
  1. Deploy your contracts:
   soroban contract deploy --wasm target/wasm32-unknown-unknown/release/cosmic_token.wasm --source alice --network testnet
   soroban contract deploy --wasm target/wasm32-unknown-unknown/release/cosmic_faucet.wasm --source alice --network testnet
Enter fullscreen mode Exit fullscreen mode

Make note of the contract IDs returned. You've just launched your cosmic creation into the Stellar testnet! 🎉

Creating a Web Interface 🖥️

Let's create a simple web interface for our faucet using HTML, CSS, and JavaScript. Create an index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cosmic Token Faucet</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #1a1a2e;
            color: #fff;
        }
        .container {
            text-align: center;
            background-color: #16213e;
            padding: 2rem;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.5);
        }
        button {
            background-color: #0f3460;
            color: white;
            border: none;
            padding: 10px 20px;
            margin-top: 20px;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #e94560;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🌠 Cosmic Token Faucet 🚰</h1>
        <p>Get your daily dose of Cosmic Tokens!</p>
        <input type="text" id="address" placeholder="Enter your Stellar address">
        <button onclick="requestTokens()">Drip Tokens</button>
        <p id="result"></p>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stellar-sdk/10.4.1/stellar-sdk.js"></script>
    <script>
        const server = new StellarSdk.Server('https://horizon-testnet.stellar.org');
        const faucetId = 'YOUR_FAUCET_CONTRACT_ID';

        async function requestTokens() {
            const address = document.getElementById('address').value;
            const resultElement = document.getElementById('result');

            try {
                const account = await server.loadAccount(address);
                const transaction = new StellarSdk.TransactionBuilder(account, { 
                    fee: StellarSdk.BASE_FEE,
                    networkPassphrase: StellarSdk.Networks.TESTNET
                })
                .addOperation(StellarSdk.Operation.invokeHostFunction({
                    function: 'drip',
                    parameters: [StellarSdk.xdr.ScVal.scvAddress(StellarSdk.Address.fromString(address))],
                    contractId: faucetId
                }))
                .setTimeout(30)
                .build();

                // You would typically sign this transaction with the user's key
                // For simplicity, we're just displaying the XDR here
                const xdr = transaction.toXDR();
                resultElement.innerText = `Transaction XDR: ${xdr}`;
            } catch (error) {
                resultElement.innerText = `Error: ${error.message}`;
            }
        }
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Replace 'YOUR_FAUCET_CONTRACT_ID' with the actual contract ID of your deployed faucet.

This creates a cosmic-themed webpage where users can input their Stellar address and request tokens. It's like a space-age ATM! 🏧🚀

Testing Our Faucet 💧

Now it's time to test our cosmic creation:

  1. Open the index.html file in a web browser.
  2. Enter a Stellar testnet address.
  3. Click the "Drip Tokens" button.
  4. You should see a transaction XDR displayed. In a real application, you would sign and submit this transaction.

Congratulations! You've just created a token faucet on Stellar! 🎉

Conclusion and Next Steps 🚀

You've taken your first steps into the cosmic world of Stellar smart contracts! You've learned how to:

  • Set up a Stellar development environment
  • Create a custom token
  • Build a token faucet smart contract
  • Deploy contracts to the Stellar testnet
  • Create a simple web interface for your faucet

But this is just the beginning of your stellar journey! Here are some ideas to take your cosmic creation to the next level:

  • Add more complex token economics (e.g., interest, staking)
  • Implement additional security measures
  • Create a more interactive and visually appealing UI
  • Explore other Stellar smart contract use cases

Remember, in the world of blockchain, the sky's not the limit – it's just the beginning! Keep exploring, keep building, and keep reaching for the stars! 🌠👨‍🚀👩‍🚀

Looking forward to reading your comments.

Top comments (0)