<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by SentinelFi on Medium]]></title>
        <description><![CDATA[Stories by SentinelFi on Medium]]></description>
        <link>https://medium.com/@sentineldefi?source=rss-d9289beb9203------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RgxQ42i3mjvZEAwKGCTI4A.png</url>
            <title>Stories by SentinelFi on Medium</title>
            <link>https://medium.com/@sentineldefi?source=rss-d9289beb9203------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 16:17:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sentineldefi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Acurast Compute for Stellar Developers: Part 2]]></title>
            <link>https://medium.com/@sentineldefi/acurast-compute-for-stellar-developers-part-2-eb82e8f661f2?source=rss-d9289beb9203------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb82e8f661f2</guid>
            <category><![CDATA[acurast]]></category>
            <category><![CDATA[decentralized-computing]]></category>
            <category><![CDATA[soroban]]></category>
            <category><![CDATA[stellar]]></category>
            <category><![CDATA[oracle]]></category>
            <dc:creator><![CDATA[SentinelFi]]></dc:creator>
            <pubDate>Fri, 31 Oct 2025 20:16:26 GMT</pubDate>
            <atom:updated>2025-10-31T20:16:26.969Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZ-RjgDHLP5oU4vJRhYafw.png" /></figure><p>In the first part of this series, we explored the fundamentals of getting started with Acurast. If you haven’t had a chance to read it yet, we highly recommend beginning <a href="https://medium.com/@sentineldefi/acurast-compute-for-stellar-developers-part-1-3fa8611d1897">there</a>.</p><p>In this tutorial, we will walk through using Acurast to create a simple weather oracle for Soroban. We will cover installing the Acurast CLI, setting up a demo project, creating a Soroban smart contract to receive data, and building an Acurast oracle application that fetches external API data and sends it to the contract.</p><h4>Table of Contents</h4><blockquote>- <a href="https://medium.com/@sentineldefi/acurast-compute-for-stellar-developers-part-2-eb82e8f661f2#6dbc">Prerequisites</a><br>- <a href="https://medium.com/@sentineldefi/acurast-compute-for-stellar-developers-part-2-eb82e8f661f2#7b81">Setting Up a Demo App with Acurast</a><br>- <a href="https://medium.com/@sentineldefi/acurast-compute-for-stellar-developers-part-2-eb82e8f661f2#0d9e">Creating a Soroban Smart Contract</a><br>- <a href="https://medium.com/@sentineldefi/acurast-compute-for-stellar-developers-part-2-eb82e8f661f2#78b2">Building and Deploying the Weather Oracle</a><br>- <a href="https://medium.com/@sentineldefi/acurast-compute-for-stellar-developers-part-2-eb82e8f661f2#932f">Verifying the Result</a><br>- <a href="https://medium.com/@sentineldefi/acurast-compute-for-stellar-developers-part-2-eb82e8f661f2#c79b">Next Steps</a></blockquote><h4>Prerequisites</h4><p>Before we begin, ensure you have the following set up:</p><ul><li><strong>Node.js (v20)</strong> and <strong>npm</strong> — Acurast processor nodes run on Node.js 20, so our code must be compatible with that version. Make sure Node.js 20.x and npm are installed on your machine.</li><li><strong>Git</strong> — for cloning and managing project templates.</li><li><strong>OS</strong> — Linux, macOS, or Windows (WSL) all support Node.js and Acurast CLI.</li><li><strong>Acurast CLI</strong> — the command-line tool to create and deploy Acurast projects. You can install it globally via npm (see instructions below).</li><li><strong>Rust and Stellar CLI</strong> — a Soroban development environment. Install Rust (v1.90 or higher) and the Stellar CLI (we use version 23.0 in this tutorial). Follow Stellar’s official <a href="https://developers.stellar.org/docs/build/smart-contracts/getting-started/setup">setup guide</a> if you need to set up Rust and the Stellar CLI.</li><li><strong>Soroban SDK</strong> — The example uses Soroban SDK v23.</li><li><strong>Stellar Testnet Account</strong> — You will need a Stellar testnet account to deploy and interact with the contract. Use the Stellar CLI to generate a keypair and <a href="http://lab.stellar.org/account/fund">fund</a> it (instructions provided below).</li><li><strong>Acurast Account</strong> — An Acurast Canary testnet account with test tokens. If you don’t have one, the Acurast CLI will help create or use an existing account during deployment. Make sure to fund your Acurast testnet account via the <a href="https://faucet.acurast.com/">Acurast Faucet</a>.</li><li><strong>OpenWeatherMap API Key</strong> — Sign up at <a href="https://openweathermap.org/api">OpenWeatherMap</a> to obtain a free API key for fetching weather data. We will use this in our oracle code to query the weather API.</li><li><strong>Some familiarity with JavaScript/TypeScript</strong> will be helpful, but you can follow along even if you are primarily a Rust/Soroban developer.</li></ul><h4>Setting Up a Demo App with Acurast</h4><p>In this section, we will create and deploy a basic Acurast project to get comfortable with the Acurast CLI workflow. The Acurast CLI allows you to scaffold projects from templates, bundle the code, and deploy to the decentralized compute network. Our first app will be a blank project that doesn’t do much, but it will verify that our environment is correctly set up.</p><p><strong>1. Install the Acurast CLI:</strong> Open a terminal and install the CLI globally via npm:</p><pre>npm install -g @acurast/cli</pre><p>Verify the installation by running acurast with no arguments, which should display the help and available commands. You should see a list of subcommands like new, init, deploy, etc., confirming the CLI is ready to use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*34o8sbKq2iwBsZGxnp0twg.png" /><figcaption>Acurast CLI</figcaption></figure><p><strong>2. Create a new Acurast project:</strong> Use the CLI to bootstrap a new project from the blank template. Run:</p><pre>acurast new demo</pre><p>This will prompt you to choose a template. Select the <a href="https://github.com/Acurast/acurast-example-apps/tree/main/templates/blank"><strong>blank template</strong> </a>(currently the only option). The CLI will clone a starter project named “demo” into a demo directory. If the template repository fails to clone due to SSH issues, ensure your Git is set up with an SSH key (you can generate one with ssh-keygen and add it to your GitHub account).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*w59nxHKvdkMJ_4OMtaRNeQ.png" /><figcaption>Acurast demo project</figcaption></figure><p><strong>3. Initialize the project:</strong> Navigate into the project folder and run the init command:</p><pre>cd demo<br>acurast init</pre><p>The acurast init step will ask a few configuration questions. For this demo, you can accept the defaults (project name &quot;demo&quot;, one-time execution, scheduling interval of &quot;5min&quot;, and output file dist/bundle.js). These settings are saved in an acurast.json file, which defines how and when your code will run on Acurast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3qAU0uT4gqKC8qMiVDWBhg.png" /><figcaption>Acurast initialization</figcaption></figure><blockquote>For details on acurast.json and environment configuration, see the <a href="https://github.com/Acurast/acurast-cli?tab=readme-ov-file#configuration-details">Acurast CLI README</a>.</blockquote><blockquote>In addition to this guide, you can refer to the <a href="https://docs.acurast.com/developers/deploy-first-app">official documentation</a> and <a href="https://www.youtube.com/watch?v=KSq-A-CJDyc">video tutorial</a>.</blockquote><p>At this point, you can open the project in your editor to examine the structure. It should resemble a standard Node.js project with a src/index.ts file (currently mostly empty, with a sample), a package.json, webpack.config.js, .env, etc., plus the Acurast-specific acurast.json file.</p><p><strong>4. Fund your Acurast account:</strong> Before deploying, ensure your Acurast testnet account has funds. When you run the acurast init command (Step 3), it outputs a new address (&quot;<em>The CLI will use the following address:</em>&quot;) and stores the account’s mnemonic in the .env file. Use the <a href="https://faucet.acurast.com/">Acurast faucet</a> to get test tokens.</p><p><strong>5. Bundle the application:</strong> Acurast deployments require your code to be bundled into a single JavaScript file. The blank template comes with a build configuration (using Webpack). Run the bundling script:</p><pre>npm run bundle</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*M2pgmaf71jlVFcyJoZ0ytA.png" /><figcaption>Acurast bundle</figcaption></figure><p>This will compile and bundle the source into <em>dist/bundle.js</em>. After running this, verify that <em>dist/bundle.js</em> exists. You can even test-run it locally with Node:</p><pre>node ./dist/bundle.js</pre><p>Since this is just the blank template, it may not output much, but ensuring it runs without errors is a good sanity check.</p><p><strong>6. Deploy to Acurast Canary testnet </strong>by running:</p><pre>acurast deploy</pre><p>The CLI will upload your bundle.js to the Acurast Canary testnet and schedule it according to your acurast.json configuration. Alternatively, you could use npm run deploy (which by default runs the bundle and then the deploy for you in one command).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZriQvsRDIRTzhWfsU9WmSQ.png" /><figcaption>Acurast deployment</figcaption></figure><p>If the deployment succeeds, congratulations. You’ve deployed your first app on Acurast! This simple demo doesn’t do much, but it confirms that your environment is working and that you can deploy code to Acurast’s decentralized compute pool. The Acurast network will have one of its processors pick up and execute your code securely.</p><p>With a basic deployment under our belt, let’s move on to the main task: building a Soroban-integrated oracle.</p><h4>Creating a Soroban Smart Contract</h4><p>Next, we will create a Soroban smart contract on the Stellar testnet to hold weather data. Our Acurast oracle will push data into this contract, and the contract will store it for retrieval. We assume you have the Soroban environment ready (Rust installed, target added, Stellar CLI installed) as noted in prerequisites. If not, set that up first.</p><p>Ensure you have the correct Stellar CLI version (this tutorial uses v23.0). You can check your Stellar CLI with stellar --version. To switch versions, use cargo install --locked stellar-cli@VERSION. Also, ensure the Rust target wasm32v1-none is added via rustup target add wasm32v1-none.</p><p><strong>1. Initialize a new Soroban project:</strong> In a suitable directory on your machine, run the Stellar CLI to create a new contract project:</p><pre>stellar contract init soroban-acurast</pre><p>This will scaffold a new Rust project in a folder named soroban-acurast (you can choose a different name). Change into that directory:</p><pre>cd soroban-acurast</pre><p><strong>2. Build and test the project:</strong> The project template includes a simple “Hello World” contract. To verify everything is working, run the tests and build the default contract:</p><pre>cargo test<br>stellar contract build</pre><p>If these commands complete without error, your Soroban toolchain is functioning.</p><p><strong>3. Set up a Stellar testnet account (“Alice”):</strong> We need a keypair to deploy and interact with our contract. Using the Stellar CLI, generate a new keypair and save it under a name (e.g., “alice”) in the global key store:</p><pre>stellar keys generate --global alice --network testnet</pre><p>This creates a new testnet keypair labeled “alice”. To view the public key (address), run:</p><pre>stellar keys address alice</pre><p>Copy the displayed public address. Now fund this account on the Stellar testnet. The easiest way is via the Stellar Laboratory <a href="http://lab.stellar.org/account/fund">Friendbot faucet</a>. Ensure the account is funded before proceeding.</p><p><strong>4. Write the weather contract:</strong> Open the lib.rs in soroban-acurast/contracts/hello-world/src. Replace the template code (the hello world example) with a simple contract that stores and retrieves weather data. For simplicity, our contract will have two functions:</p><ul><li>set_weather(temp: i32, description: String) – to be called by our oracle, storing the given temperature and description in the contract’s persistent storage.</li><li>get_weather() -&gt; Option&lt;WeatherData&gt; – to retrieve the last stored weather data.</li></ul><p>For demonstration, we’ll not implement any access control (anyone can call set_weather). Below is an example implementation of such a contract:</p><pre>#![no_std]<br>use soroban_sdk::{contract, contractimpl, contracttype, symbol_short, Env, String, Symbol};<br><br>#[contracttype]<br>#[derive(Clone, Debug, Eq, PartialEq)]<br>pub struct WeatherData {<br>    pub temperature: i32,<br>    pub description: String,<br>    pub timestamp: u64,<br>}<br><br>const WEATHER_KEY: Symbol = symbol_short!(&quot;WEATHER&quot;);<br><br>#[contract]<br>pub struct WeatherContract;<br><br>#[contractimpl]<br>impl WeatherContract {<br>    pub fn set_weather(env: Env, temperature: i32, description: String) {<br>        let weather_data = WeatherData {<br>            temperature,<br>            description,<br>            timestamp: env.ledger().timestamp(),<br>        };<br>        // Store the weather data in instance storage<br>        env.storage().instance().set(&amp;WEATHER_KEY, &amp;weather_data);<br>    }<br><br>    pub fn get_weather(env: Env) -&gt; Option&lt;WeatherData&gt; {<br>        // Retrieve the latest saved weather data from instance storage<br>        env.storage().instance().get(&amp;WEATHER_KEY)<br>    }<br>}</pre><p>In this contract, we use the Soroban SDK to write temperature data, description, and a timestamp to instance storage under the key &quot;WEATHER&quot;. The get_weather function returns an Option that will be None if no weather has been set yet. In a more advanced contract, we might include multiple entries, but this simple design suffices for now.</p><blockquote><strong>Note:</strong> This example is for demonstration purposes and not hardened for production use.</blockquote><p>Remove any unnecessary template files (for example, you can delete test.rs). Make sure the contract code compiles:</p><pre>stellar contract build</pre><p><strong>5. Optimize and deploy the contract:</strong></p><pre>stellar contract optimize --wasm target/wasm32v1-none/release/hello_world.wasm</pre><blockquote><strong>Note:</strong> Adjust the path to the .wasm file if your project name differs.</blockquote><p>Now deploy the optimized contract to the Stellar testnet:</p><pre>stellar contract deploy \<br>  --wasm target/wasm32v1-none/release/hello_world.optimized.wasm \<br>  --source alice --network testnet --alias weather</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NaW3M92nhNTYh39POz0RoQ.png" /><figcaption>Soroban contract deployment</figcaption></figure><p>After running this, the CLI will output a <strong>contract ID</strong>. Save this contract ID, we will need it soon for the oracle. You can verify the contract deployment by checking that the contract appears on the network. For example, you can visit the Stellar Expert explorer with your contract ID:</p><p><a href="https://stellar.expert/explorer/testnet/contract/YourContractID/storage">https://stellar.expert/explorer/testnet/contract/YourContractID/storage</a></p><p>Now that we have a Soroban contract ready to receive data, let’s build the Acurast oracle app that will fetch real-world weather information and call set_weather on this contract.</p><h4>Building and Deploying the Weather Oracle</h4><p>In this section, we’ll create a new Acurast project specifically for our weather oracle logic. This project will use a script to call an external API and then submit the data to the Soroban contract using the <a href="https://www.npmjs.com/package/@stellar/stellar-sdk/">Stellar JS SDK</a>. We will then deploy this oracle to run on Acurast’s decentralized network.</p><ol><li><strong>Scaffold a new Acurast project for the oracle </strong>(just as we did with the demo earlier):</li></ol><pre>acurast new soroban-oracle<br>cd soroban-oracle<br>acurast init</pre><p>When running acurast init for this project, choose <strong>one-time run</strong> (since we want the job to execute once per deployment, or you could schedule it periodically if desired). Set the maximum execution time to about <em>30 seconds</em> (the oracle shouldn&#39;t take longer than this to fetch API data and submit a transaction). Other settings can be left as default.</p><p><strong>2. Install Stellar SDK in the project:</strong> Our oracle code will use the Stellar JavaScript SDK to interact with the Soroban contract. Install the SDK as a dependency:</p><pre>npm install @stellar/stellar-sdk</pre><p>At the time of writing, version 14.2.0 of @stellar/stellar-sdk is compatible with this tutorial. You can check for the latest version, anything in the 14.x series or above should work.</p><p><strong>3. Write the oracle code:</strong> Open src/index.ts in your editor. We will implement the logic to fetch weather data from <a href="https://openweathermap.org/">OpenWeatherMap</a> and then invoke our Soroban contract’s set_weather function with that data.</p><p>Below is a simplified version of the oracle code:</p><pre>import { Keypair, Networks , contract} from &quot;@stellar/stellar-sdk&quot;;<br><br>const API_KEY = &#39;your_openweathermap_api_key&#39;; // Obtain free API key after signing up at https://home.openweathermap.org/users/sign_up <br>const CITY = &#39;San Francisco&#39;;<br>const API_URL = `https://api.openweathermap.org/data/2.5/weather?q=${CITY}&amp;appid=${API_KEY}&amp;units=metric`;<br><br>const RPC_URL = &quot;https://soroban-testnet.stellar.org&quot;;<br>const NETWORK = Networks.TESTNET;<br>const KEYPAIR = Keypair.fromSecret(&#39;your_testnet_stellar_secret_key&#39;); // Secret key for testnet account generated by the CLI (do not use this for production with real account)<br>const CONTRACT_ID = &quot;your_testnet_soroban_contract_id&quot;; // Your Soroban smart contract ID deployed on testnet<br><br>declare const _STD_: any;<br><br>if (typeof _STD_ === &quot;undefined&quot;) {<br>  // If _STD_ is not defined, we know it&#39;s not running in the Acurast Cloud.<br>  // Define _STD_ here for local testing.<br>  console.log(&quot;Running in local environment&quot;);<br>  (global as any)._STD_ = {<br>    app_info: { version: &quot;local&quot; },<br>    job: { getId: () =&gt; &quot;local&quot; },<br>    device: { getAddress: () =&gt; &quot;local&quot; },<br>  };<br>}<br><br>async function getCurrentWeather() {<br>  try {<br>    console.log(&quot;Calling weather API...&quot;);<br>    const response = await fetch(API_URL);<br>    if (!response.ok) {<br>      throw new Error(`HTTP error! status: ${response.status}`);<br>    }<br>    const data = await response.json();<br>    const weatherInfo = {<br>      city: data.name,<br>      country: data.sys.country,<br>      temperature: Math.round(data.main.temp),<br>      feelsLike: Math.round(data.main.feels_like),<br>      humidity: data.main.humidity,<br>      description: data.weather[0].description,<br>      windSpeed: data.wind.speed,<br>      pressure: data.main.pressure<br>    };<br>    console.log(&#39;Current weather:&#39;);<br>    console.log(`Temperature: ${weatherInfo.temperature}°C (feels like ${weatherInfo.feelsLike}°C)`);<br>    console.log(`Conditions: ${weatherInfo.description}`);<br>    console.log(`Humidity: ${weatherInfo.humidity}%`);<br>    console.log(`Wind Speed: ${weatherInfo.windSpeed} m/s`);<br>    console.log(`Pressure: ${weatherInfo.pressure} hPa`);<br>    return weatherInfo;<br>  } catch (error) {<br>    console.error(&#39;Error fetching weather data:&#39;, error);<br>  }<br>}<br><br>async function callContract(temp: number, desc: string) {<br>  console.log(&quot;Temperature:&quot;, temp, &quot; - &quot;, typeof temp);<br>  console.log(&quot;Description:&quot;, desc, &quot; - &quot;, typeof desc);<br>  const { signTransaction } = contract.basicNodeSigner(KEYPAIR, NETWORK);<br>  const client : any = await contract.Client.from({<br>    contractId: CONTRACT_ID,<br>    networkPassphrase: NETWORK,<br>    rpcUrl: RPC_URL,<br>    publicKey: KEYPAIR.publicKey(),<br>    signTransaction,<br>  });<br>  console.log(&quot;Calling smart contract...&quot;);<br>  try {<br>    const transaction = await client.set_weather({<br>      temperature: temp,<br>      description: desc,<br>    });<br>    let { result: setWeatherResult } = await transaction.signAndSend();<br>    console.log(&#39;Contract response:&#39;);<br>    console.log(setWeatherResult);<br>  } catch (e) {<br>    console.log(&quot;Error calling contract:&quot;, e);<br>  }<br>}<br><br>async function compute() {<br>  try {<br>    const weatherResponse = await getCurrentWeather();<br>    console.log(&quot;Weather Finished&quot;);<br>    if (!weatherResponse) throw new Error(&quot;Weather response is undefined&quot;);<br>    const _ = await callContract(weatherResponse.temperature, weatherResponse.description);<br>    console.log(&quot;Contract Finished&quot;);<br>  } catch (error) {<br>    console.error(&quot;Error:&quot;, error);<br>  }<br>}<br><br>compute();</pre><p>Let’s break down what this code is doing:</p><ul><li>It uses fetch API (which might already be available in Node or can be installed) to call the OpenWeatherMap API for <strong>San Francisco</strong> (you can change the city or make it configurable). We use metric units to get temperature in Celsius.</li><li>It extracts the temperature (rounded to an integer) and the weather description from the API response.</li><li>We construct a Soroban invocation operation by specifying the contract ID, the testnet network passphrase, the Soroban RPC URL, and the associated public key. Once defined, we call the desired function by name (set_weather), and provide the required arguments.</li><li>We sign the transaction with Alice’s key and submit it to the network.</li><li>If successful, the contract’s set_weather will execute, storing the temperature and description in the contract.</li></ul><blockquote><strong>Note:</strong> The above code is a conceptual example for demonstration purposes. The key takeaway is that the oracle fetches external data and then sends a transaction to call the Soroban contract. The code provided in this example is one approach, but other methods or SDK helpers could be used.</blockquote><p>After writing the code, <strong>replace the placeholders</strong>:</p><ul><li>your_openweathermap_api_key – with your actual <a href="https://home.openweathermap.org/api_keys">API key</a>.</li><li>your_testnet_soroban_contract_id – with the Soroban weather contract ID obtained from deployment earlier.</li><li>your_testnet_stellar_secret_key – with the secret key of the Alice account (you can get the secret via stellar keys show alice if you created it with the CLI).</li></ul><blockquote>In production and more advanced use cases, you would typically configure the secret key and other settings through environment variables.</blockquote><p><strong>4. Test the oracle locally:</strong> Before deploying to Acurast, run the oracle code on your local machine to ensure it works. First, bundle the project:</p><pre>npm run bundle</pre><p>Then execute the bundled file with Node:</p><pre>node ./dist/bundle.js</pre><p>This will run the compute() function. Watch the console output for any errors or confirmations. Ideally, you should see the fetched weather data logged (e.g., temperature and description) and a message that a transaction was submitted. You can check the Stellar testnet (e.g., using Stellar Explorer) to see if the contract storage updated immediately, since this local run is actually sending a transaction to the network. If it worked, you&#39;ve essentially done the oracle process locally.</p><ul><li>If you encounter an SSL certificate error when the Node script tries to connect to the Soroban RPC (this can happen on some systems), you may need to update your root certificates. For example, on Ubuntu you might run:</li></ul><pre>sudo apt-get update &amp;&amp; sudo apt-get install --reinstall ca-certificates<br>export NODE_OPTIONS=&quot;--use-openssl-ca&quot;<br>export NODE_EXTRA_CA_CERTS=&quot;/etc/ssl/certs/ca-certificates.crt&quot;</pre><p>This ensures Node trusts the SSL certs. After this, try running the bundle again.</p><p><strong>5. Deploy the oracle to Acurast:</strong> Once the local test is successful, deploy your oracle app to the Acurast network:</p><pre>npm run deploy</pre><p>This will bundle (if not already bundled) and deploy the project in one go. The job will be sent to Acurast’s Canary testnet. Acurast will schedule the execution (with one-time scheduling, it should execute shortly after deployment). Essentially, one of the decentralized Acurast processors will download your bundle.js and run the script, performing the same steps you tested locally, but now in a trust-minimized, decentralized manner.</p><p>Give it some time. There isn’t an immediate console output for you to see when it runs on Acurast, but we can verify it by checking the contract state on the blockchain.</p><h4>Verifying the Result</h4><p>After the Acurast oracle has run, we want to confirm that our Soroban smart contract received the data.</p><p>To verify the result, we will check the storage of the Soroban contract on the Stellar testnet:</p><ul><li>Go to the Stellar Expert explorer and look up your contract by ID. You can use the URL pattern:<br> <a href="https://stellar.expert/explorer/testnet/contract/YourContractID/storage"><strong>https://stellar.expert/explorer/testnet/contract/YourContractID/storage</strong></a></li></ul><p>Replace YourContractID with the actual contract ID from earlier. This page will show the contract’s storage entries. If everything worked, you should see an entry for the key &quot;WEATHER&quot; with the stored values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CeJ3_S7-Rf7umTr1GNKfLA.png" /><figcaption>Contract storage</figcaption></figure><p>Another way to verify is by calling the contract’s get_weather function using the Stellar CLI or SDK. For instance, you can use:</p><pre>stellar contract invoke --id YourContractID --network testnet --source alice --send=no -- get_weather</pre><p>This should return the weather data that was set. If it returns None, then the oracle might not have executed yet or something went wrong.</p><p>If the weather data is stored, <strong>congratulations</strong> – you have successfully built a working oracle! Your Acurast application fetched real-world data and delivered it on-chain to your Soroban smart contract.</p><h4>Next Steps</h4><p>In this tutorial, we demonstrated a basic integration of Acurast with Soroban: from off-chain data fetch to on-chain storage. There are many ways to expand and improve this setup:</p><ul><li><strong>Make the oracle more robust:</strong> You could add error handling, retries for the API fetch, or data validation. Perhaps schedule the oracle to run periodically (e.g., every hour) by adjusting the acurast.json schedule, so the contract gets regular updates.</li><li><strong>Security and authorization:</strong> In a real scenario, you might want to restrict who can call set_weather on the contract (so only your oracle or authorized sources can update data). Soroban offers ways to enforce authorization.</li><li><strong>Use environment variables:</strong> Instead of hard-coding secrets or API keys in the code, Acurast allows using environment variables (via the .env file) for things like API_KEY or secret keys, which is more secure and flexible.</li><li><strong>Explore Acurast capabilities:</strong> Acurast can do more than simple one-off jobs. It supports scheduled tasks, event-triggered tasks, and offers a decentralized infrastructure powered by smartphones. You could explore running more complex computations or integrating with other ecosystems and services.</li></ul><p>We encourage you to continue experimenting. Now that you have a working oracle, you can build more complex cross-chain or off-chain integrations for your Stellar dApps. Acurast provides a powerful tool to extend Soroban’s reach beyond the Stellar network, tapping into real-world data and computations in a decentralized way.</p><p>Happy coding, and we look forward to seeing what you build! If you have questions or feedback, feel free to reach out via the <a href="https://stellar.org/community">Stellar developer community</a> channels.</p><blockquote>Written by the Sentinel team.</blockquote><h4>Additional Resources</h4><ul><li>The official Acurast Examples repository: <a href="https://github.com/Acurast/acurast-example-apps/tree/main/apps"><strong>https://github.com/Acurast/acurast-example-apps/tree/main/apps</strong></a></li><li>An example of a decentralized price oracle (external project): <a href="https://github.com/acelonoracle/acelon-oracle"><strong>https://github.com/acelonoracle/acelon-oracle</strong></a></li><li>The Acurast Documentation: <a href="https://docs.acurast.com/"><strong>https://docs.acurast.com/</strong></a></li><li>The Acurast CLI tool source, configuration details: <a href="https://github.com/Acurast/acurast-cli"><strong>https://github.com/Acurast/acurast-cli</strong></a></li><li>Stellar Developer Docs: <a href="https://developers.stellar.org/docs"><strong>https://developers.stellar.org/docs</strong></a></li><li>A Docker image of the Acurast Canary testnet node available on Docker Hub: <a href="https://hub.docker.com/r/acurast/node-canary/tags"><strong>https://hub.docker.com/r/acurast/node-canary/tags</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb82e8f661f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Acurast Compute for Stellar Developers: Part 1]]></title>
            <link>https://medium.com/@sentineldefi/acurast-compute-for-stellar-developers-part-1-3fa8611d1897?source=rss-d9289beb9203------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fa8611d1897</guid>
            <category><![CDATA[decentralized-computing]]></category>
            <category><![CDATA[soroban]]></category>
            <category><![CDATA[acurast]]></category>
            <category><![CDATA[oracle]]></category>
            <category><![CDATA[stellar]]></category>
            <dc:creator><![CDATA[SentinelFi]]></dc:creator>
            <pubDate>Fri, 31 Oct 2025 20:15:39 GMT</pubDate>
            <atom:updated>2025-10-31T20:42:33.684Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZ-RjgDHLP5oU4vJRhYafw.png" /></figure><p><a href="https://stellar.org/soroban">Soroban</a>, Stellar’s smart contracts platform, enables on-chain logic, though developers may require access to off-chain data or computation. Unlike Ethereum’s ecosystem (which offers services like <a href="https://docs.chain.link/chainlink-functions">Chainlink Functions</a> for Web2 data), Soroban developers currently cannot fetch external APIs or run heavy computation directly from their contracts. This tutorial series addresses that gap. In <strong>Part 1</strong>, we introduce <strong>Acurast</strong>, a decentralized compute network, and explain how it can integrate off-chain data and computation into your Stellar projects. The goal is to help Stellar developers leverage Acurast to extend their Soroban smart contracts with secure, off-chain functionality.</p><blockquote>We assume you’re already familiar with Stellar and Soroban. If not, check the <a href="https://developers.stellar.org/">official Stellar documentation</a>. Here we focus on <strong>why Acurast is valuable to Stellar</strong>, what problems it solves, and what concepts and tools you need to get started.</blockquote><h4>Table of Contents</h4><blockquote>- <a href="https://medium.com/@sentineldefi/acurast-compute-for-stellar-developers-part-1-3fa8611d1897#65f5">What is Acurast</a><br>- <a href="https://medium.com/@sentineldefi/acurast-compute-for-stellar-developers-part-1-3fa8611d1897#de78">Why Stellar Developers Should Care</a><br>- <a href="https://medium.com/@sentineldefi/acurast-compute-for-stellar-developers-part-1-3fa8611d1897#e07c">Decentralized Compute</a><br>- <a href="https://medium.com/@sentineldefi/acurast-compute-for-stellar-developers-part-1-3fa8611d1897#3e18">DePIN (Decentralized Physical Infrastructure Network)</a><br>- <a href="https://medium.com/@sentineldefi/acurast-compute-for-stellar-developers-part-1-3fa8611d1897#7740">Trusted Execution Environment (TEE)</a><br>- <a href="https://medium.com/@sentineldefi/acurast-compute-for-stellar-developers-part-1-3fa8611d1897#9d00">Hardware Security Module (HSM)</a><br>- <a href="https://medium.com/@sentineldefi/acurast-compute-for-stellar-developers-part-1-3fa8611d1897#da6a">Supported Wallets, Networks, and Tokens</a><br>- <a href="https://medium.com/@sentineldefi/acurast-compute-for-stellar-developers-part-1-3fa8611d1897#c935">Ecosystem Readiness</a><br>- <a href="https://medium.com/@sentineldefi/acurast-compute-for-stellar-developers-part-1-3fa8611d1897#e155">Conclusion</a></blockquote><h4>What is Acurast</h4><p><a href="https://acurast.com/">Acurast</a> is a <strong>decentralized, verifiable compute network powered by smartphones</strong>. It enables users to run secure applications on a decentralized infrastructure at scale<strong>, without relying on centralized servers</strong> or cloud providers. In simpler terms, Acurast transforms everyday devices (personal smartphones) into a globally distributed “cloud” that can perform computations and deliver data to blockchains. The network architecture leverages hardware-backed security (trusted execution environments, described later) to ensure that computations are <strong>trustworthy and private</strong>, even though they happen off-chain on someone’s phone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*NZJ38Ucqlrir8KjNHwJIVw.png" /><figcaption>Acurast smartphone clusters</figcaption></figure><p>Key features of Acurast’s design include decentralization, verifiability, scalability, and confidentiality. Smartphones act as compute providers, and each device runs tasks in a secure enclave so that <strong>user data remains owned by the user and is never exposed</strong> during processing. Acurast was founded in 2022 to tackle blockchain and Web3 challenges (such as oracles and decentralized infrastructure) with this smartphone-powered model.</p><p>According to <a href="https://docs.acurast.com/">official documentation</a>, Acurast has onboarded over <strong>131,000 phones</strong> as compute units across the globe, supported by a community of more than <strong>75,000 participants</strong> active in 140+ countries. The testnet network has already processed <strong>hundreds of millions of transactions</strong>, demonstrating scalability. The platform operates as a built-in <strong>job marketplace</strong> for compute tasks: developers (requesters) can post off-chain jobs, and smartphone owners (providers) execute those jobs and earn rewards. Using smartphones offers huge advantages in cost and energy efficiency (phones are affordable and consume very little power compared to servers).</p><p>Under the hood, Acurast’s blockchain uses a variant of <strong>Nominated Proof-of-Stake (NPoS)</strong> consensus for security. This means participants stake the network’s native token to secure and validate compute tasks. We won’t dive deep into the consensus design here, but it’s designed to keep the network decentralized and robust. For a detailed look at Acurast’s multi-layer architecture (application layer, execution layer, consensus, etc.), see the Acurast’s <a href="https://docs.acurast.com/acurast-protocol/architecture/architecture/">architecture documentation</a> or their <a href="https://arxiv.org/pdf/2503.15654">research paper</a>.</p><h4>Why Stellar Developers Should Care</h4><p>Soroban smart contracts cannot directly fetch external data or run off-chain computations, which limits what your dApp can do with real-world information. For example, a Soroban contract can’t on its own retrieve a web API response, compute a complex algorithm (like machine learning inference), or verify an event that happened on another blockchain. In the Ethereum world, developers solve these problems with oracle networks and services, but on Stellar these capabilities are still emerging.</p><p>By using Acurast, Stellar developers can <strong>bridge their smart contracts to the outside world</strong> in a secure and decentralized manner. In essence, Acurast acts as an <strong>off-chain compute and data provider</strong> for Soroban:</p><ul><li><strong>Access real-world data:</strong> Fetch data from the Internet (APIs, web services), for example, sports scores, weather information, stock prices, and deliver it into your Soroban contract in near real-time, with cryptographic proof of authenticity.</li><li><strong>Off-load heavy computations:</strong> Perform complex or expensive calculations off-chain and only return the results on-chain. This could be running AI/ML models, image or audio processing, large financial simulations, etc., that would be infeasible to do within Soroban’s environment due to cost or speed constraints.</li><li><strong>Generate verifiable randomness:</strong> Obtain random numbers (for games, lotteries, NFTs, etc.) generated inside a secure enclave on a phone, along with proof that the process was fair. This can substitute for a VRF or on-chain randomness function.</li><li><strong>Bridge across chains and services:</strong> Use Acurast as a relay to connect with other blockchains or off-chain systems. For example, an Acurast task could watch an Ethereum contract or a Web2 API and then trigger a Soroban contract with a verified update. Cross-chain data transfer becomes possible without trusting a centralized server.</li><li><strong>Keep sensitive logic off-chain:</strong> If your application has parts that involve confidential data or algorithms (user identities, secret keys, proprietary algorithms), you can execute those parts off-chain within a Trusted Execution Environment (TEE) on an Acurast device. Only a sanitized or encrypted result is passed back to your contract, preserving privacy while still leveraging blockchain for the end result.</li></ul><p>In short, <strong>Acurast unlocks off-chain data access and computation for Stellar</strong>. It fills a crucial gap: until Soroban has native oracle support or services like Chainlink integrated, Acurast scripts can serve as custom oracles and compute agents for your dApps. A few <a href="https://developers.stellar.org/docs/data/oracles/oracle-providers">oracle providers</a> are beginning to appear in the Stellar ecosystem (e.g. Reflector, DIA, Band Protocol) but these focus mostly on price feeds. General-purpose off-chain compute or fetching arbitrary APIs is still <strong>limited but growing</strong> on Stellar. Acurast distinguishes itself by allowing <strong>arbitrary code execution in a verifiable way</strong>. This makes it a flexible tool for developers.</p><blockquote><strong>Real-world example:</strong> Suppose you’re building a Soroban-based dApp that needs weather data. Soroban alone can’t call a weather API. With Acurast, you could deploy a script that fetches weather info from a trusted API, runs inside a phone’s secure enclave, and then posts the temperature or rainfall data into your smart contract. Because the phone provides an attestation (proof) of the computation, your contract knows the data is authentic and untampered. This kind of pattern (off-chain query and on-chain consume) can be applied to countless use cases (sports results for prediction markets, sensor readings for IoT contracts, off-chain vote counts for governance, you name it).</blockquote><p>Let’s clarify some key concepts that Acurast builds upon.</p><h4>Decentralized Compute</h4><p><strong>Decentralized compute</strong> refers to any system where computing power is provided by many independent nodes or devices rather than a single centralized server or data center. In such a system, tasks are distributed across a network of participants. This contrasts with traditional cloud computing, where a few big providers run all the computations. Acurast is an example of decentralized compute: instead of one company’s servers, <em>thousands of individual smartphones</em> around the world collectively perform computations for the network. This improves resilience (no single point of failure) and aligns with blockchain’s ethos of decentralization.</p><h4>DePIN (Decentralized Physical Infrastructure Network)</h4><p><strong>DePIN</strong> stands for <strong>Decentralized Physical Infrastructure Network</strong>. This is a class of projects that use blockchain incentives to decentralize real-world infrastructure and services. Participants contribute physical resources, such as hardware devices, sensors, bandwidth, or in Acurast’s case, compute power, and are rewarded with tokens for their contributions. By doing so, DePIN projects create alternatives to traditional centralized infrastructure.</p><p>Acurast is a textbook example of a DePIN project. It takes a piece of physical infrastructure (compute hardware) and decentralizes it: anyone with a smartphone can join and provide computing services. The network’s security and coordination are managed on-chain (through Acurast’s protocol and token economics), but the actual computing work happens on user-provided devices. Contributors (smartphone owners) are rewarded in Acurast’s native tokens for running tasks, which incentivizes growth of the network. The end result is a <strong>community-owned cloud</strong> that doesn’t rely on any third-party, instead, it runs on spare phones and devices people already have.</p><p>For more on DePIN, see:</p><ul><li><a href="https://www.kraken.com/learn/what-is-depin">https://www.kraken.com/learn/what-is-depin</a></li><li><a href="https://arxiv.org/pdf/2406.02239">https://arxiv.org/pdf/2406.02239</a></li></ul><h4>Trusted Execution Environment (TEE)</h4><p>A <strong>Trusted Execution Environment (TEE)</strong> is a secure area of a device’s processor where code can run isolated from the main operating system. Think of it like a tamper-proof enclave inside the CPU, even if the phone’s normal OS is compromised or malware-infested, the code running in the TEE remains secure and cannot be altered or spied on from the outside. TEEs use hardware-backed encryption and access controls to protect the data and code within them. Many modern smartphones come with TEEs (for example, ARM’s TrustZone technology) which are typically used for sensitive tasks like fingerprint authentication, mobile payments, or secure key storage.</p><p>In a blockchain context, TEEs are extremely useful: they allow you to perform computations off-chain with a guarantee that the code was executed correctly and privately. The TEE can produce an <strong>attestation</strong>, a cryptographic proof that “<em>I ran this code with these inputs, and here are the outputs, and I haven’t been tampered with.</em>” Acurast leverages this capability heavily. When an Acurast smartphone node executes your job, it can return an attestation signature to prove the result is authentic. This gives your smart contract confidence in the off-chain result without needing to trust the device owner.</p><p><strong>In Acurast’s network, every compute provider uses their phone’s TEE to ensure tasks are executed securely and confidentially.</strong> The TEE keeps the computation results hidden from the phone’s owner or any malware, so providers cannot cheat or peek at private data they might be processing. Additionally, Acurast uses the phone’s hardware security module (HSM, next topic) to verify that each device is genuine (not an emulated environment) and meets the security requirements. This combination means that even though computations happen off the Stellar chain, they are done in a <strong>“trust-minimized”</strong> way. The blockchain can trust the result because it’s backed by hardware evidence, not just a third-party server’s word.</p><h4>Hardware Security Module (HSM)</h4><p>A <strong>Hardware Security Module (HSM)</strong> is a dedicated piece of hardware designed to securely manage cryptographic keys and operations. Traditional HSMs are often external devices or smart cards used by banks and enterprises to safeguard keys (for example, for signing transactions or certificates) in a way that they can never be extracted or compromised. In everyday terms, an HSM is like a vault for cryptographic secrets that can also perform cryptographic functions (signing, encryption) internally. Even someone with physical access to the machine can’t easily get the keys out of an HSM.</p><p>Smartphones actually include HSM-like components as part of their secure hardware. For instance, the secure enclave on an iPhone or the Titan M chip on Google phones serve this role: they store encryption keys, biometric data, etc., and ensure those secrets never leave the chip unencrypted. In Acurast, these capabilities are used to <strong>prove the identity and integrity of each phone in the network</strong>. When a phone joins Acurast as a processor, the network can challenge it to attest via its HSM/TEE that “<em>I am a real device with the expected hardware and OS, not a modified or virtual machine.</em>” This <strong>remote attestation</strong> process (often part of TEE functionality) is crucial for trust. It prevents someone from emulating thousands of fake phones to cheat the network, only real hardware with proper HSM/TEE credentials can participate.</p><p>By leveraging HSMs, Acurast ensures that off-chain computations are not just secure in execution, but also <strong>coming from legitimate, trusted hardware</strong>.</p><blockquote>Smartphones’ built-in TEEs and secure hardware modules form the backbone of Acurast’s trust model. Each task runs in an isolated enclave, and each device provides cryptographic proof of correct execution. Combining TEEs and HSMs in this way allows Acurast to deliver <strong>confidential and verifiable off-chain compute</strong>. As a developer, this means you can rely on results coming from Acurast as if they were produced on-chain, you get proofs and signatures to validate in your smart contract. Sensitive data can be handled off-chain without being exposed, and complex processes can be off-loaded without sacrificing trust. In summary, Acurast creates a “trustless oracle” environment: even though the compute happens in someone else’s phone, you don’t have to simply trust that person or device, as the hardware ensures the integrity of the computation.</blockquote><p>Now that we’ve covered the core concepts, let’s move on to the practical aspects of using Acurast as a Stellar developer.</p><h4>Supported Wallets, Networks, and Tokens</h4><p>To interact with Acurast (for deploying scripts or paying for compute), you’ll need to set up the proper wallets and use the correct network. Acurast has its own blockchain environment distinct from Stellar, so think of it like using a separate chain alongside Stellar.</p><h4>Wallets</h4><p>Acurast currently supports a few wallet options for managing accounts on its network:</p><ul><li><strong>MetaMask</strong></li><li><strong>WalletConnect</strong></li><li><strong>Talisman</strong></li><li><strong>Phantom</strong></li><li><strong>Ledger</strong></li><li><strong>AirGap</strong></li><li><strong>SubWallet</strong></li></ul><p>You can create or import an account via these wallets and connect to Acurast’s network. Refer to the official <a href="https://docs.acurast.com/wallets/wallet-overview">Acurast Wallets</a> guide for detailed steps on setting up a wallet and address.</p><blockquote>The above list is non-exhaustive, but covers the main options at the time of writing.</blockquote><h4>Networks</h4><p>Acurast provides different networks for development and production, similar to how Stellar has testnet and public mainnet:</p><ul><li><strong>Canarynet (Testnet) </strong>— The canarynet has its own token (cACU) used for testing and incentives.</li><li><strong>Devnet</strong> — A development network that may be used for early-stage testing.</li><li><strong>Mainnet (upcoming)</strong> — The <strong>Acurast Genesis Mainnet</strong> is anticipated to launch in 2025. Once mainnet is live, it will use the ACU token and be the real production environment for Acurast tasks.</li></ul><blockquote>As a Stellar developer starting out, you will be deploying to the testnet (canary network) initially.</blockquote><blockquote>You can find the necessary <a href="https://docs.acurast.com/networks/">network information</a> in the official docs.</blockquote><h4>Tokens and Fees</h4><p>Acurast has a native token that powers its network economy:</p><ul><li><strong>cACU</strong> (testnet) — This is what you will use to pay for tasks on testnet and what providers earn for completing tasks.</li><li><strong>ACU </strong>(mainnet) — The token for the upcoming mainnet.</li></ul><p>The Acurast token is used for <strong>transaction fees, staking, settlement, and governance</strong> on the network. For our purposes, when you deploy a compute job, you will pay in these tokens for the execution. The cost might depend on the complexity of the job and how many devices need to run it. Compute providers (phone operators) stake tokens to secure their participation and get rewarded in tokens for executing jobs.</p><p>For testing, you can get free cACU tokens from the <strong>Acurast Faucet</strong> at <a href="https://faucet.acurast.com/"><strong>faucet.acurast.com</strong></a>. This is similar to how Stellar’s Friendbot gives test XLM. Make sure to fund your wallet via the faucet before trying to use Acurast’s testnet.</p><blockquote>For more on tokenomics and utility, see the <a href="https://docs.acurast.com/tokenomics/#token-utility">Acurast docs</a>.</blockquote><h4>Ecosystem Readiness</h4><p>As of now, <strong>Stellar (Soroban) is not officially integrated as </strong><a href="https://docs.acurast.com/integrations/"><strong>Acurast’s natively supported blockchains</strong></a>. However, this doesn’t mean you can’t use Acurast with Stellar. It just means you have to do a bit of manual work. Essentially, you can write an Acurast off-chain script that interacts with Stellar by calling Stellar’s Horizon API or Soroban RPC endpoints. The script could, for instance, fetch data and then submit a transaction to your Soroban contract with that data.</p><p>Because Soroban isn’t “plug-and-play” in Acurast at this time, your Acurast job code must handle details like <strong>encoding data in XDR, managing Stellar tx signatures, and calling Soroban functions</strong>. It’s an extra layer of effort, but quite doable. Presumably, official support may come in the future as both ecosystems mature.</p><blockquote>In <a href="https://medium.com/@sentineldefi/acurast-compute-for-stellar-developers-part-2-eb82e8f661f2">Part 2</a> of this series, we’ll explore a practical example of writing such an Acurast script for a Soroban contract.</blockquote><p><strong>Acurast Hub:</strong> Acurast has introduced a web interface called <a href="https://hub.acurast.com/"><strong>Acurast Hub</strong></a> to make interacting with the network easier. The Hub provides a <strong>dashboard</strong> for viewing network stats, your account balance, managing deployments, and monitoring your connected phones if you’re providing compute. For Stellar developers using Acurast, the Hub isn’t strictly necessary, but it’s a helpful tool. You can, for example, use it to register your wallet, browse existing “jobs” on the network, or inspect logs of your compute tasks.</p><p><a href="https://acelon.io/oracle-builder"><strong>Acelon Project</strong></a><strong>:</strong> You might also hear about <strong>Acelon</strong> in the context of Acurast. Acelon is a project spun off by the Acurast team focusing specifically on <em>on-demand data feeds on-chain</em>. It provides an interface to configure things like price feeds (choose currency pairs, exchanges, aggregation methods, etc., and it generates code for those). Essentially, Acelon is tackling the oracle use-case in a more packaged way. <em>Currently, Stellar is </em><strong><em>not</em></strong><em> supported by Acelon</em>, as it’s early and primarily geared toward other networks.</p><h4>Conclusion</h4><p>In summary, <strong>the Acurast ecosystem is growing rapidly</strong>, but Stellar integration is on the horizon rather than available out-of-the-box today. By getting started now (on the testnet) you’ll be ahead of the curve for when official support or mainnet goes live. <strong>Part 2</strong> of this series will guide you through writing and deploying an Acurast job that works with a Soroban contract, showing the practical steps and code involved.</p><p><em>Thanks for reading Part 1.</em> In <a href="https://medium.com/@sentineldefi/acurast-compute-for-stellar-developers-part-2-eb82e8f661f2">Part 2</a>, we will walk through a hands-on example of integrating Acurast with a Soroban smart contract. If you have questions or feedback, feel free to reach out via the <a href="https://stellar.org/community">Stellar developer community</a> channels.</p><blockquote>Written by the Sentinel team.</blockquote><h4>Additional Resources</h4><ul><li><a href="https://docs.acurast.com/">https://docs.acurast.com/</a></li><li><a href="https://acurast.medium.com/">https://acurast.medium.com/</a></li><li><a href="https://hub.acurast.com/">https://hub.acurast.com/</a></li><li><a href="https://arxiv.org/pdf/2503.15654">https://arxiv.org/pdf/2503.15654</a></li><li><a href="https://developers.stellar.org/docs/data/oracles/oracle-providers">https://developers.stellar.org/docs/data/oracles/oracle-providers</a></li><li><a href="https://stellar.org/learn/smart-contract-basics-oracles">https://stellar.org/learn/smart-contract-basics-oracles</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fa8611d1897" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NFT Contract on Soroban with OpenZeppelin]]></title>
            <link>https://medium.com/@sentineldefi/nft-contract-on-soroban-with-openzeppelin-538587ac1bc8?source=rss-d9289beb9203------2</link>
            <guid isPermaLink="false">https://medium.com/p/538587ac1bc8</guid>
            <category><![CDATA[stellar]]></category>
            <category><![CDATA[non-fungible-tokens]]></category>
            <category><![CDATA[soroban]]></category>
            <category><![CDATA[openzeppelin]]></category>
            <category><![CDATA[nft]]></category>
            <dc:creator><![CDATA[SentinelFi]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 16:48:01 GMT</pubDate>
            <atom:updated>2025-10-28T16:48:01.522Z</atom:updated>
            <content:encoded><![CDATA[<p>In this turorial, we’ll walk through creating and minting non-fungible tokens (NFTs) on Stellar’s <a href="https://stellar.org/soroban">Soroban</a> contract platform using <a href="https://www.openzeppelin.com/">OpenZeppelin’s</a> SEP-50 compliant implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CjKfgxvDnSOPRXWLOA0zgQ.png" /></figure><h3>Table of Contents</h3><blockquote><em>- </em><a href="https://medium.com/@sentineldefi/nfts-contract-on-soroban-with-openzeppelin-538587ac1bc8#0e34"><em>Prerequisites</em></a><em><br></em><strong><em>- </em></strong><a href="https://medium.com/@sentineldefi/nfts-contract-on-soroban-with-openzeppelin-538587ac1bc8#1af0"><em>Using the OpenZeppelin Wizard to Scaffold the NFT Contract</em></a><em><br></em><strong><em>- </em></strong><a href="https://medium.com/@sentineldefi/nfts-contract-on-soroban-with-openzeppelin-538587ac1bc8#a3f9"><em>NFT Contract Features Explained</em></a><em><br></em><strong><em>- </em></strong><a href="https://medium.com/@sentineldefi/nfts-contract-on-soroban-with-openzeppelin-538587ac1bc8#e34d"><em>Code Changes</em></a><em><br></em><strong><em>- </em></strong><a href="https://medium.com/@sentineldefi/nfts-contract-on-soroban-with-openzeppelin-538587ac1bc8#c3ba"><em>Building and Deploying the Contract</em></a><em><br></em><strong><em>- </em></strong><a href="https://medium.com/@sentineldefi/nfts-contract-on-soroban-with-openzeppelin-538587ac1bc8#bea1"><em>Minting Your First NFT</em></a><em><br></em><strong><em>- </em></strong><a href="https://medium.com/@sentineldefi/nfts-contract-on-soroban-with-openzeppelin-538587ac1bc8#20db"><em>Setting Up a Simple UI with OpenZeppelin UI Builder</em></a><em><br></em><strong><em>- </em></strong><a href="https://medium.com/@sentineldefi/nfts-contract-on-soroban-with-openzeppelin-538587ac1bc8#6ecc"><em>Next Steps and Ideas</em></a><em><br></em><strong><em>- </em></strong><a href="https://medium.com/@sentineldefi/nfts-contract-on-soroban-with-openzeppelin-538587ac1bc8#3e13"><em>Additional Resources</em></a></blockquote><h3>Prerequisites</h3><p>Before you begin, make sure your development environment is set up for Soroban: you’ll need Rust installed, the wasm32v1-none target, and the Stellar CLI. If you haven’t already, follow the official Stellar <a href="https://developers.stellar.org/docs/build/smart-contracts/getting-started/setup">setup guide</a>.</p><p>A brief understanding of NFTs would also help: <a href="https://www.investopedia.com/non-fungible-tokens-nft-5115211">https://www.investopedia.com/non-fungible-tokens-nft-5115211</a></p><h3>Using the OpenZeppelin Wizard to Scaffold the NFT Contract</h3><p>Instead of building from scratch, we’ll use OpenZeppelin’s Stellar Wizard to generate an NFT contract template. The wizard supports a <em>NonFungible</em> template that’s SEP-50 compliant (similar to Ethereum’s <a href="https://ethereum.org/developers/docs/standards/tokens/erc-721/">ERC-721</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*74sCrd7bh3gMkKYaxP59qA.png" /><figcaption>OpenZeppelin Wizard: <a href="https://wizard.openzeppelin.com/stellar#nonfungible">https://wizard.openzeppelin.com/stellar#nonfungible</a></figcaption></figure><ol><li>Go to OpenZeppelin Wizard Stellar and switch to the <strong><em>NonFungible </em></strong>tab: <a href="https://wizard.openzeppelin.com/stellar#nonfungible">https://wizard.openzeppelin.com/stellar#nonfungible</a></li><li>Under <strong>Settings </strong>on the left, enter your NFT collection’s metadata. Set the <strong>name</strong> (e.g. &quot;SentinelNFT&quot;), <strong>symbol</strong> (e.g. &quot;SNTL&quot;). The <strong>base_uri </strong>is currently hard-coded as &quot;www.mytoken.com&quot;. The wizard will combine the base URI with each token’s ID to form token_uri for metadata. In practice, you might later host per-NFT metadata on IPFS and update the base URI.</li><li>In <strong>Features</strong>, select any extensions you need. For this tutorial, we’ll enable <strong>Burnable</strong> (so tokens can be destroyed) and <strong>Enumerable</strong> (so we have the ability to list all tokens and those owned by a user).</li><li>In <strong>Minting</strong>, choose <strong>Sequential</strong> so token IDs are auto-incremented (you could also use “Non-Sequential” for custom IDs).</li><li>For <strong>Access Control</strong>, select <strong>Ownable. </strong>This means the contract owner will have exclusive rights to certain privileged functions (like minting).</li><li>(Optional) In <strong>Info</strong>, you can add a license or security metadata. We’ll leave the default MIT license.</li><li>After those steps, click <strong>Download (Rust Development Package)</strong> to get the starter project.</li></ol><p>The wizard generated a NFT contract skeleton. It includes setting the metadata and a simple mint function controlled by the owner. The generated code will look like this:</p><pre>// SPDX-License-Identifier: MIT<br>// Compatible with OpenZeppelin Stellar Soroban Contracts ^0.4.1<br><br>use soroban_sdk::{contract, contractimpl, Address, Env, String};<br>use stellar_access::ownable::{self as ownable, Ownable};<br>use stellar_macros::{default_impl, only_owner};<br>use stellar_tokens::non_fungible::{<br>    burnable::NonFungibleBurnable,<br>    enumerable::{Enumerable, NonFungibleEnumerable},<br>    Base, NonFungibleToken,<br>};<br><br>#[contract]<br>pub struct SentinelNFT;<br><br>#[contractimpl]<br>impl SentinelNFT {<br>    pub fn __constructor(e: &amp;Env, owner: Address) {<br>        let uri = String::from_str(e, &quot;www.mytoken.com&quot;);<br>        let name = String::from_str(e, &quot;SentinelNFT&quot;);<br>        let symbol = String::from_str(e, &quot;SNTL&quot;);<br>        Base::set_metadata(e, uri, name, symbol);<br>        ownable::set_owner(e, &amp;owner);<br>    }<br><br>    #[only_owner]<br>    pub fn mint(e: &amp;Env, to: Address) {<br>        Enumerable::sequential_mint(e, &amp;to);<br>    }<br>}<br><br>#[default_impl]<br>#[contractimpl]<br>impl NonFungibleToken for SentinelNFT {<br>    type ContractType = Enumerable;<br>}<br><br>//<br>// Extensions<br>//<br><br>#[default_impl]<br>#[contractimpl]<br>impl NonFungibleBurnable for SentinelNFT {}<br><br>#[default_impl]<br>#[contractimpl]<br>impl NonFungibleEnumerable for SentinelNFT {}<br><br>//<br>// Utils<br>//<br><br>#[default_impl]<br>#[contractimpl]<br>impl Ownable for SentinelNFT {}</pre><blockquote><strong>Note:</strong> The #[only_owner] attribute on mint ensures only the owner can mint. You can remove it if you want anyone to be able to mint tokens.</blockquote><h3>NFT Contract Features Explained</h3><p>OpenZeppelin’s SEP-50 NFT implementation supports several features and extensions. Briefly:</p><ul><li><strong>Burnable:</strong> Lets you destroy tokens. Internally it removes the token’s entry from persistent storage.</li><li><strong>Consecutive (Batch Minting):</strong> Stores ownership only at boundaries, inferring it for intermediate IDs. This greatly reduces storage writes for batch minting, but isn’t needed if you mint tokens one by one.</li><li><strong>Enumerable:</strong> Enables on-chain enumeration. It keeps lists of all token IDs and all IDs owned by each user.</li><li><strong>Royalties:</strong> Allows setting default or per-token royalty info (basis points and recipient).</li><li><strong>Pausable:</strong> (Not used here) Would let you pause contract operations in certain situations.</li><li><strong>Upgradeable:</strong> (Not used here) Provides proxy-based upgrades.</li><li><strong>Access Control (Ownable/Roles):</strong> By choosing <strong>Ownable</strong>, we give a single account full control of certain contract functions. Alternatively, a roles-based scheme could allow multiple roles with different permissions.</li><li>For more details, OpenZeppelin’s Stellar Soroban docs explain these traits and extensions: <a href="https://docs.openzeppelin.com/stellar-contracts/tokens/non-fungible/non-fungible">https://docs.openzeppelin.com/stellar-contracts/tokens/non-fungible/non-fungible</a>. In our example, we included <strong>Burnable</strong>, <strong>Enumerable</strong>, and <strong>Ownable</strong>.</li></ul><h3>Code Changes</h3><p>After downloading and extracting the Wizard’s generated package, open the project in your preferred IDE. You’ll see the generated contract under contracts/non_fungible/src/contract.rs. The root Cargo.toml already includes dependencies on OpenZeppelin’s Stellar Soroban crates (e.g., stellar-tokens, stellar-access).</p><blockquote>At the time of writing, the version of those crates is 0.4.1.</blockquote><p>Change the package name in contracts/non_fungible/Cargo.toml to &quot;nft&quot; (or any desired).</p><p>Notice how the mint function in the code above calls Enumerable::sequential_mint(e, &amp;to). That will mint the next token ID to the given address. Thanks to the Enumerable extension, the contract also keeps track of total supply and user’s NFTs. Because of Ownable, only the owner can call mint. You can modify or extend these behaviors (for example, adding a public sale function or roles) later.</p><h3>Building and Deploying the Contract</h3><p>With the code in place, build the contract to generate a WASM artifact. In the project root, open the terminal and run:</p><pre>stellar contract build</pre><p>You should see output like:</p><pre>ℹ️ Build Summary:<br>   Wasm File: target\wasm32v1-none\release\nft.wasm<br>   Wasm Hash: 048299882113199ee2562b6ee8a95f0dab9838ad9f290f951b374b8d2a64aef0<br>   Exported Functions: 23 found<br>     • _<br>     • __constructor<br>     • accept_ownership<br>     • approve<br>     • approve_for_all<br>     • balance<br>     • burn<br>     • burn_from<br>     • get_approved<br>     • get_owner<br>     • get_owner_token_id<br>     • get_token_id<br>     • is_approved_for_all<br>     • mint<br>     • name<br>     • owner_of<br>     • renounce_ownership<br>     • symbol<br>     • token_uri<br>     • total_supply<br>     • transfer<br>     • transfer_from<br>     • transfer_ownership<br>✅ Build Complete</pre><p>Next, optimize the WASM to reduce size (recommended):</p><pre>stellar contract optimize --wasm target/wasm32v1-none/release/nft.wasm</pre><p>This should report something like:</p><pre>Reading: target/wasm32v1-none/release/nft.wasm (18728 bytes)<br>Optimized: target/wasm32v1-none/release/nft.optimized.wasm (16304 bytes)</pre><p>Now let’s deploy to the Stellar testnet. First, create or use a testnet account for the deployer. We’ll call it nft. If you don’t have one funded, run:</p><pre>stellar keys generate nft --network testnet --fund<br>stellar keys address nft</pre><p>The first command creates a keypair labeled nft and funds it on testnet. The second shows its public address.</p><p>Then deploy the contract with:</p><pre>stellar contract deploy --wasm target/wasm32v1-none/release/nft.wasm --source-account nft --network testnet --alias sntl -- --owner nft</pre><ul><li>--source-account nft --network testnet: uses your nft account on testnet.</li><li>--alias sntl: gives the contract a local alias.</li><li>The -- --owner nft passes the owner address to the constructor.</li></ul><p>You should see output like:</p><pre>ℹ️  Skipping install because wasm already installed<br>ℹ️  Using wasm hash 048299882113199ee2562b6ee8a95f0dab9838ad9f290f951b374b8d2a64aef0<br>ℹ️  Simulating deploy transaction…<br>ℹ️  Transaction hash is TX_HASH<br>🔗 https://stellar.expert/explorer/testnet/tx/TX_HASH<br>ℹ️  Signing transaction: TX_HASH<br>🌎 Submitting deploy transaction…<br>🔗 https://stellar.expert/explorer/testnet/contract/CONTRACT_ID<br>✅ Deployed!<br>CONTRACT_ID</pre><p>Save the CONTRACT_ID (and the URLs) for later. You can verify the deployment on <a href="https://stellar.expert/explorer/testnet">Stellar Expert’s</a> explorer. For example, visiting https://stellar.expert/explorer/testnet/contract/CONTRACT_ID (replacing CONTRACT_ID) will show your contract’s details on testnet.</p><blockquote><strong>Tip:</strong> If tools or commands change in the future, check the official Stellar docs or Discord for updates.</blockquote><h3>Minting Your First NFT</h3><p>Now that the contract is live on testnet, let’s mint the first token (the “genesis” NFT) to yourself. Using Stellar CLI, invoke the mint function:</p><pre>stellar contract invoke --id sntl --source-account nft --network testnet -- mint --to nft</pre><p>The output should look like:</p><pre>ℹ️ Signing transaction: TX_HASH<br>📅 CONTRACT_ID - Success - Event: [{&quot;symbol&quot;:&quot;mint&quot;},{&quot;address&quot;:&quot;USER_ADDRESS&quot;}] = {&quot;u32&quot;:0}</pre><p>This indicates the mint succeeded and token ID 0 was created. You can verify on Stellar Expert under contract storage: your address should now appear under <strong>OwnerTokens</strong> at index 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*NjIU9fUbtQZsJfUzKjXVaw.png" /><figcaption><a href="https://stellar.expert/explorer/testnet/contract/CONTRACT_ID/storage">https://stellar.expert/explorer/testnet/contract/CONTRACT_ID/storage</a></figcaption></figure><p>Congratulations! You’ve deployed a contract and minted (probably) your first genesis NFT on Stellar!</p><p>Feel free to play with the contract: try minting more tokens to different addresses, burning them, or transferring between accounts.</p><h3>Setting Up a Simple UI with OpenZeppelin UI Builder</h3><p>To give the contract a user interface, we can use the OpenZeppelin UI Builder, which is in early development but handy for quick demos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8jWJljukn9KGY8BPvxkiLA.png" /><figcaption>OpenZeppelin UI Builder: <a href="https://builder.openzeppelin.com/">https://builder.openzeppelin.com/</a></figcaption></figure><ol><li>Go to <a href="https://builder.openzeppelin.com/">https://builder.openzeppelin.com/</a>. Select <strong>Stellar</strong> as the blockchain and <strong>Testnet</strong> as the network.</li><li>Enter your deployed contract ID. The builder will load the contract (you should see something like “<em>Contract … loaded successfully with 22 functions</em>”). Click <em>Next</em>.</li><li>For “Select Contract Function”, choose <strong>Mint</strong>. This will create a simple form for calling mint function.</li><li>In the <strong>General</strong> tab, you can set a title (e.g. “Mint NFT”) and description (e.g. “Mint our Stellar NFT”). Under <strong>Fields</strong>, you might change the placeholder to “Enter recipient address”.</li><li>Leave <strong>Execution Method</strong> tab settings as default, and choose the <strong>Stellar Wallets Kit</strong> for <strong>UI Kit</strong>. Then click Next and proceed to <strong>Export </strong>the form.</li><li>Extract (unzip) the downloaded folder (e.g., named mint-address-form). In that folder, run pnpm install (or use npm install).</li><li>In the public/ folder of the UI project, rename app.config.json.example to app.config.json. Then run:</li></ol><pre>pnpm run dev</pre><p>This should open http://localhost:3000/ (Vite app) in your browser with a basic mint form.</p><p>Install a Stellar wallet (like <a href="https://www.freighter.app/">Freighter</a>), if not already. Import your nft account into the wallet using its secret key (run stellar keys show nft in the terminal to get it).</p><p>On the UI page, you should now be able to connect the wallet using the connect wallet button.</p><blockquote><strong>Note:</strong> The OpenZeppelin UI Builder is in active development, you might run into styling and other issues or bugs. If so, you can report them on <a href="https://github.com/OpenZeppelin/ui-builder">OpenZeppelin’s UI Builder GitHub</a>.</blockquote><h3>Next Steps and Ideas</h3><p>With the basics done, there are many ways to expand your NFT project:</p><ul><li>Upload your digital assets (images, music, etc.) to IPFS or Arweave. Use the IPFS URI as the base URI in your contract, so token’s JSON metadata can point to your asset files.</li><li>Enable the royalties extension to set creator fees on secondary sales.</li><li>If you need bulk minting or burning, consider the Consecutive extension or adding batch functions.</li><li>For non-transferable tokens, you could modify the contract to disable transfer, making them Soulbound tokens.</li><li>Write Rust tests for your NFT contract.</li><li>Experiment with integrating your NFT contract into larger dApp or game logic.</li><li>Deploy your UI to a hosting platform and share it with others.</li></ul><p>The possibilities are endless!</p><p>Thank you for following along this NFT journey on Stellar Soroban! We hope this tutorial was helpful and encouraging. If you found it useful, please share your experiences and ideas with the <a href="https://stellar.org/community">Stellar community</a>.</p><blockquote>Written by the Sentinel team.</blockquote><h4><strong>Additional Resources:</strong></h4><ul><li>Stellar Soroban Docs: <a href="https://developers.stellar.org/docs/build/smart-contracts/example-contracts/non-fungible-token">https://developers.stellar.org/docs/build/smart-contracts/example-contracts/non-fungible-token</a></li><li>OpenZeppelin Stellar Soroban Docs: <a href="https://docs.openzeppelin.com/stellar-contracts/tokens/non-fungible/non-fungible">https://docs.openzeppelin.com/stellar-contracts/tokens/non-fungible/non-fungible</a></li><li>Stellar Developer Meeting: Demo of OpenZeppelin UI Builder: <a href="https://www.youtube.com/watch?v=-uTKQIQpwAU">https://www.youtube.com/watch?v=-uTKQIQpwAU</a></li><li>Creating NFTs using ‪OpenZeppelin‬ Stellar Soroban library: <a href="https://www.youtube.com/watch?v=xA1HfckPqFs">https://www.youtube.com/watch?v=xA1HfckPqFs</a></li><li>OpenZeppelin UI Builder GitHub: <a href="https://github.com/OpenZeppelin/ui-builder">https://github.com/OpenZeppelin/ui-builder</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=538587ac1bc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing a Tokenized Vault on Stellar Soroban]]></title>
            <link>https://medium.com/@sentineldefi/implementing-a-tokenized-vault-on-stellar-soroban-33a7cda08649?source=rss-d9289beb9203------2</link>
            <guid isPermaLink="false">https://medium.com/p/33a7cda08649</guid>
            <category><![CDATA[vault]]></category>
            <category><![CDATA[soroban]]></category>
            <category><![CDATA[erc4626]]></category>
            <category><![CDATA[stellar]]></category>
            <category><![CDATA[openzeppelin]]></category>
            <dc:creator><![CDATA[SentinelFi]]></dc:creator>
            <pubDate>Mon, 13 Oct 2025 09:32:27 GMT</pubDate>
            <atom:updated>2025-10-13T12:55:51.276Z</atom:updated>
            <content:encoded><![CDATA[<p>Decentralized finance (DeFi) platforms often offer users to deposit assets into <strong>vaults</strong> and receive <strong>vault tokens</strong> (shares) in return. These vault tokens represent the user’s share of the pooled assets in the vault, and as the vault generates yield or profits, the value of these shares increases. Later, users can withdraw their assets (plus yield) by redeeming the vault tokens. Some vault protocols have accumulated millions in total value locked (TVL), generating significant revenue through yield or fees. In this tutorial, we’ll explore how to implement a simple tokenized vault on <a href="https://stellar.org/soroban"><strong>Stellar Soroban</strong></a>, following the style of Ethereum’s ERC-4626 tokenized vault standard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*5S6RdHA1W94mSv_d6Dc9Pw.png" /><figcaption>A conceptual diagram of a tokenized vault. User deposits underlying assets into the vault and receives vault shares representing the stake. Later, user can redeem/burn those shares to withdraw the underlying assets plus yield from the vault.</figcaption></figure><h4>Table of Contents</h4><blockquote>- <a href="https://medium.com/@sentineldefi/implementing-a-tokenized-vault-on-stellar-soroban-33a7cda08649#710f">What is a Tokenized Vault?</a><br><strong>- </strong><a href="https://medium.com/@sentineldefi/implementing-a-tokenized-vault-on-stellar-soroban-33a7cda08649#e975">Why Use a Standard Like ERC-4626?</a><br><strong>- </strong><a href="https://medium.com/@sentineldefi/implementing-a-tokenized-vault-on-stellar-soroban-33a7cda08649#a9b1">Vault Structure: Underlying Asset, Shares, and Decimals Offset</a><br><strong>- </strong><a href="https://medium.com/@sentineldefi/implementing-a-tokenized-vault-on-stellar-soroban-33a7cda08649#4025">Vault Functions (Interface)</a><br><strong>- </strong><a href="https://medium.com/@sentineldefi/implementing-a-tokenized-vault-on-stellar-soroban-33a7cda08649#4f96">Vault Events</a><br><strong>- </strong><a href="https://medium.com/@sentineldefi/implementing-a-tokenized-vault-on-stellar-soroban-33a7cda08649#de4d">Conversion Formulas and Initial Exchange Rate</a><br><strong>- </strong><a href="https://medium.com/@sentineldefi/implementing-a-tokenized-vault-on-stellar-soroban-33a7cda08649#db4f">Building and Deploying a Soroban Vault (Step-by-Step)</a><br><strong>- </strong><a href="https://medium.com/@sentineldefi/implementing-a-tokenized-vault-on-stellar-soroban-33a7cda08649#96f1">Ideas for Extensions and Real-World Applications</a><br><strong>- </strong><a href="https://medium.com/@sentineldefi/implementing-a-tokenized-vault-on-stellar-soroban-33a7cda08649#0aee">Conclusion and Next Steps</a></blockquote><h4>What is a Tokenized Vault?</h4><p>A <strong>tokenized vault</strong> is a smart contract that pools funds by allowing users to deposit an underlying asset (e.g. <em>XLM </em>or <em>USDC</em>) and mints <strong>vault share tokens</strong> in return. These share tokens represent the depositor’s proportional ownership of the vault’s assets. As the vault uses the deposited funds for various strategies (yield farming, lending, staking, etc.), the underlying assets can grow. When a user withdraws, their share tokens are burned, and they receive their portion of the underlying assets (including any yield earned). In essence, a vault token is like a receipt for your deposit that also accrues value over time.</p><p>Tokenized vaults are a fundamental DeFi primitive. They enable use cases such as yield aggregation (automatically earning interest from multiple sources), lending/borrowing pools, staking pools, insurance funds, and even prediction market pools. By holding vault share tokens, users have a liquid representation of their claim on the pooled assets, which they could potentially transfer or use elsewhere while the assets remain in the vault earning yield.</p><h4>Why Use a Standard Like ERC-4626?</h4><p>In the Ethereum ecosystem, the <a href="https://ethereum.org/developers/docs/standards/tokens/erc-4626/"><strong>ERC-4626</strong> standard</a> was introduced to provide a unified interface for yield-bearing vaults. Before standards, each DeFi project implemented vaults with different function names and behaviors, leading to fragmentation and duplicated effort. ERC-4626 defines a common set of vault functions (for depositing, withdrawing, converting, checking balances, etc.) so that integrators and developers can work with any compliant vault in a consistent way. This saves development time and reduces mistakes by <strong>not reinventing the wheel</strong> for every project. It also enables <strong>easier composability</strong>, for example, one protocol can deposit into any ERC-4626 vault knowing the interface is standard.</p><p><strong>Stellar Soroban</strong> is Stellar’s smart contract platform, and developers are bringing similar standards to Soroban. <a href="https://www.openzeppelin.com/">OpenZeppelin</a>, a leading smart contract library provider, has introduced a Vault extension (ERC-4626 style) for Soroban as of version 0.5.0-rc.1 (<a href="https://github.com/OpenZeppelin/stellar-contracts/releases">release candidate</a>). While this is not yet an official Stellar standard (ongoing SEP discussion is in progress), it is likely to become a go-to pattern for building vaults on Stellar Soroban. Using a well-audited, standardized implementation means implementers benefit from best practices and security reviews. In short, standards like ERC-4626 on Soroban make vault development faster, safer, and more interoperable.</p><blockquote>Technical note: The Soroban vault implementation is provided as an <strong>extension of Stellar’s </strong><a href="https://developers.stellar.org/docs/tokens/token-interface"><strong>SEP-41 Token Interface</strong></a>. This means the vault itself is a token contract (for the share token) that inherits all the standard token functions like transfers, balance checks, allowances, etc. In other words, a vault is a token (the share token), with additional vault-specific functionality.</blockquote><h4>Vault Structure: Underlying Asset, Shares, and Decimals Offset</h4><p>Before diving into code, let’s understand the structure of a vault contract on Soroban:</p><ul><li><strong>Underlying Asset:</strong> The vault is tied to a single underlying token (e.g., the Stellar USDC token contract or a XLM contract). Users deposit this asset into the vault. The underlying asset must be a SEP-41 compliant fungible token contract. The standard vault supports only one type of underlying asset per vault.</li><li><strong>Vault Share Token:</strong> The vault contract <em>itself</em> represents the share token. When users deposit assets, the vault mints share tokens to them. When users withdraw, the vault burns their share tokens. The share token follows the SEP-41 interface (similar to ERC-20) for fungibility. Implementers can configure the share token’s name and symbol on initialization (for example, “Vault Token” with symbol “VLT”).</li><li><strong>Decimals and Decimals Offset:</strong> Every token has a certain number of decimal places for its units. If the underlying asset has d decimals, the vault share token will typically use d + offset decimals. This <strong>decimals offset</strong> is a crucial security parameter to mitigate <a href="https://docs.openzeppelin.com/contracts/5.x/erc4626#security-concern-inflation-attack"><strong>vault inflation attack</strong></a>.</li></ul><p><strong>What is an inflation attack?</strong> It’s a subtle exploit where an attacker can manipulate the exchange rate of a vault when it’s empty or contains very few assets. For example, if a vault starts empty, an attacker could deposit a tiny amount (getting a tiny number of shares), then <em>donate</em> a large amount of underlying to the vault (sending the underlying asset directly to the vault contract, without calling its deposit function), increasing totalAssets without minting new shares. This skews the assets-per-share ratio in their favor. A subsequent honest user might deposit assets but receive almost zero shares (since the vault’s asset-per-share price was artificially inflated), effectively losing their deposit to the attacker.</p><p>To prevent this, the OpenZeppelin vault design uses a <a href="https://docs.openzeppelin.com/contracts/5.x/erc4626#defending-with-a-virtual-offset"><strong>virtual offset</strong></a> in the conversion formula. The vault starts with a <em>phantom initial supply</em> of 10^offset shares and 1 unit of asset in the math (without actually having any real assets or minting any token). This ensures the initial exchange rate isn’t extremely low and makes it unprofitable to perform the donation attack. In practice, this means if the vault is empty, the first real deposit will mint shares at a rate as if there was already some minimal assets and shares. The larger the offset (i.e., more extra decimal precision in shares), the more the attacker’s donation gets diluted and the less they can exploit rounding. The offset essentially forces the vault’s share price to a safe baseline when empty. You can read more about this inflation attack and the virtual offset in <a href="https://docs.openzeppelin.com/contracts/5.x/erc4626">OpenZeppelin’s documentation</a>.</p><p>In summary, when constructing a vault we need to specify: the underlying asset address and the decimals offset value. The vault will then set its share token’s decimals = underlying token’s decimals + offset. For example, if the underlying token has 7 decimals (like XLM) and we choose offset = 6, the vault share token will have 13 decimals. The offset provides extra precision to safeguard the conversion math.</p><h4>Vault Functions (Interface)</h4><p>The vault interface introduces a number of functions specific to depositing and withdrawing assets, on top of the standard token functions inherited for the share token. Let’s break down these <strong>vault-specific functions</strong> and their purposes. We will also note which functions are <strong>read-only</strong> (just calculate or retrieve data) and which are <strong>state-changing</strong> (perform an action on-chain):</p><h4>Read-Only Vault Functions (View Functions)</h4><ul><li><strong>query_asset()</strong> – <em>view:</em> Returns the address of the underlying asset token that the vault accepts and that was set during the vault’s initialization. This lets anyone identify what token the vault is pooling.</li><li><strong>total_assets()</strong> – <em>view:</em> Returns the total amount of underlying assets currently held by the vault. This typically equals the vault’s holdings of the underlying token (including any yield earned and not yet withdrawn).</li><li><strong>total_supply()</strong> – <em>view:</em> Returns the total supply of vault share tokens in circulation. It represents the sum of all shares that have been minted minus any burned shares. This value, together with total_assets(), helps determine the current exchange rate of assets per share.</li><li><strong>convert_to_shares(assets)</strong> – <em>view:</em> Given an amount of underlying assets, this function calculates how many <strong>shares</strong> would be minted for that amount. It uses the current exchange rate formula. For example, if the vault currently has a 1:1 ratio and you input 100 assets, you’d get ~100 shares (subject to rounding and offset adjustments). This is a pure calculation (does not actually transfer or mint anything).</li><li><strong>convert_to_assets(shares)</strong> – <em>view:</em> The inverse of the above, it calculates how many <strong>assets</strong> would be redeemable for a given number of vault shares at the current rate. For instance, if you have 50 shares and the current exchange rate is 1 asset per share, this returns 50 assets (again, purely computational).</li><li><strong>max_deposit(receiver)</strong> – <em>view:</em> Returns the maximum amount of underlying assets that can be deposited on behalf of receiver in a single call. In many implementations this might return a very large number (i128::MAX) if there’s no specific cap, or it could be limited by vault strategy conditions. Essentially, it’s a hint of how much you <em>could</em> deposit.</li><li><strong>preview_deposit(assets)</strong> – <em>view:</em> Simulates a deposit of a certain amount of assets and returns the number of shares that would be minted. This is effectively the same calculation as convert_to_shares, but it’s part of the standard to explicitly allow users to preview an action, without actually doing the deposit.</li><li><strong>max_mint(receiver)</strong> – <em>view:</em> Similar to max_deposit, but for the <strong>mint</strong> operation. It returns the max number of shares that can be minted for receiver in one call. If no specific cap, it may be a very large number.</li><li><strong>preview_mint(shares)</strong> – <em>view:</em> Simulates minting a certain number of shares and calculates how many underlying assets would be required for that mint. If you want to mint certain amount of shares, this tells you how many assets you’d need to deposit. It uses the conversion rate formula inversely (essentially similar to convert_to_assets).</li><li><strong>max_withdraw(owner)</strong> – <em>view:</em> Returns the maximum amount of underlying assets that the given owner could withdraw from the vault. This usually corresponds to the amount of assets equivalent to the shares that owner currently holds (or possibly less if there are withdrawal limits or fees).</li><li><strong>preview_withdraw(assets)</strong> – <em>view:</em> Simulates withdrawing a certain amount of assets and reports how many shares would be required (burned) to do so. It helps a user determine “<em>If I want X assets out, how many of my vault tokens will be burned?</em>”.</li><li><strong>max_redeem(owner)</strong> – <em>view:</em> Returns the maximum number of <strong>shares</strong> that the owner could redeem for underlying assets. This is often just the owner’s share balance (or possibly the same limit as max_withdraw expressed in shares).</li><li><strong>preview_redeem(shares)</strong> – <em>view:</em> Simulates redeeming a given number of share tokens and returns how many underlying assets would be returned. For example, redeeming 10 shares might return ~10 assets at a 1:1 rate. This is the mirror of preview_withdraw.</li></ul><p>All the above functions are <strong>read-only</strong> and do not modify contract state. They can be called without submitting a transaction (in Soroban they can be invoked in a simulation context). These are useful for UIs and for other contracts to integrate with the vault.</p><blockquote>Technical note:<br>convert_to_shares provides an idealized, fee-neutral conversion rate. This is useful for general conversion queries. By contrast, <em>preview_deposit</em> returns the exact outcome of a deposit under current conditions, which is critical for user-facing accuracy.</blockquote><blockquote>The two functions are intentionally kept separate so each can evolve or be overridden for specific scenarios. Whenever a vault imposes conditions that reduce the actual shares a user receives (relative to the ideal rate), these adjustments must appear in <em>preview_deposit</em> but not in <em>convert_to_shares</em>. A common example is deposit fees. The same principle applies to other vault functions.</blockquote><blockquote>The specification explicitly states when a function MUST include fees and when it should remain fee-excluded. This distinction is subtle but important for integrators and vault designers.</blockquote><h4>State-Changing Vault Functions (Deposits &amp; Withdrawals)</h4><p>Now for the <strong>actions</strong> that move assets and mint/burn tokens. These functions will create or destroy vault share tokens and correspondingly handle the underlying asset transfers. In Soroban, these require transaction authorization by the appropriate accounts (we’ll note the operator parameter usage):</p><ul><li><strong>deposit(assets, receiver, from, operator)</strong> – <em>write:</em> Deposits a given amount of underlying assets from the from account into the vault, and mints the appropriate amount of vault share tokens to the receiver account. The operator (the caller of the function) must be authorized to spend the underlying tokens. In our Soroban’s vault implementation example, we’ll call operator.require_auth() to ensure the call is signed by the operator. On success, this returns the number of shares minted (which should equal preview_deposit(assets) result). Internally, the vault will transfer the specified assets from the operator to itself (this assumes the operator previously approved the vault to spend their tokens, if required by the underlying asset contract).</li><li><strong>mint(shares, receiver, from, operator)</strong> – <em>write:</em> An alternative to deposit, this mints exactly the specified number of shares to the receiver, and in exchange, pulls in whatever amount of underlying assets is needed from the from address. This is useful if a user cares about how many share tokens they receive (perhaps to get a round number), rather than specifying the asset amount. As with deposit, the operator must authorize and supply the assets, and the function will return the amount of assets actually deposited (should equal preview_mint(shares)).</li><li><strong>withdraw(assets, receiver, owner, operator)</strong> – <em>write:</em> Withdraws a given amount of underlying assets from the vault to the receiver, and burns the necessary shares from the owner&#39;s balance. In Soroban’s vault, the operator (caller) must be authorized to act – this could be the same as the owner or someone approved. The function calculates how many shares need to be burned to get the desired assets out (using the current exchange rate, effectively preview_withdraw). It then burns those shares from the owner and transfers the assets from the vault to the receiver. Commonly, receiver, owner and operator will be the same (withdrawing your own funds to yourself), but the separation allows flexibility (e.g. you authorize a contract or another user to withdraw on your behalf). On success, returns the number of shares burned (which should equal preview_withdraw(assets)).</li><li><strong>redeem(shares, receiver, owner, operator)</strong> – <em>write:</em> Redeems a specified number of vault shares from the owner and sends the equivalent amount of underlying assets to the receiver. This is the mirror of withdraw: the caller specifies how many share tokens to cash out, and the vault calculates how many underlying assets that corresponds to (effectively preview_redeem). It then burns the shares and transfers the assets out. As with withdraw, the operator must be authorized to perform this action, and typically operator = owner = receiver for personal withdrawals. This returns the amount of assets released (which should equal preview_redeem(shares)).</li></ul><p>All four of these functions (deposit, mint, withdraw, redeem) are <strong>state-changing</strong>. They will require a transaction and appropriate authorization. In a typical implementation, each of these functions should call operator.require_auth() to ensure that only authorized accounts can invoke them. They also interact with the underlying asset contract (transferring tokens) and update the vault’s accounting (minting/burning shares, updating total supply).</p><p><strong>Difference between deposit vs. mint, and withdraw vs. redeem:</strong> Deposit/withdraw let you specify an exact asset amount to transfer, whereas mint/redeem let you specify an exact share amount to mint or burn. They are two sides of the same coin. Depending on what the user wants to fix (the asset amount or the share amount), one pair of functions will be more convenient. Under the hood, they use the same conversion logic.</p><h4>Vault Events</h4><p>The vault emits two important events to notify off-chain or on-chain listeners about deposits and withdrawals. These events mirror the ERC-4626 specification:</p><p><strong>Deposit Event:</strong> Emitted whenever underlying assets are deposited into the vault and share tokens are minted (i.e., when the deposit/mint operation succeeds). In Soroban, events have <strong>topics</strong> (indexed fields) and <strong>data</strong> (unindexed fields). For the Deposit event:</p><p><strong>Topics:</strong></p><ol><li>The Address that initiated the deposit.</li><li>The Address that provided the underlying assets.</li><li>The Address that received the vault shares.</li></ol><p><strong>Data:</strong></p><ul><li>An i128 value for the amount of underlying assets deposited.</li><li>An i128 value for the amount of vault shares minted to the receiver.</li></ul><p><strong>Withdraw Event:</strong> Emitted whenever underlying assets are withdrawn from the vault and shares are burned (i.e., when the withdraw/redeem operation succeeds).</p><p><strong>Topics:</strong></p><ol><li>The Address that initiated the withdrawal.</li><li>The Address that received the underlying assets out of the vault.</li><li>The Address of the owner whose shares were burned.</li></ol><p><strong>Data:</strong></p><ul><li>An i128 for the amount of underlying assets withdrawn.</li><li>An i128 for the amount of vault shares burned.</li></ul><p>These events are helpful for transparency and for UIs or other contracts to track vault activity.</p><h4>Conversion Formulas and Initial Exchange Rate</h4><p>One of the core mechanics of a tokenized vault is the exchange rate between the <strong>underlying asset</strong> and the <strong>vault share token</strong>. This rate determines how many shares you get per asset when depositing and how many assets you get per share when withdrawing. The conversion is typically linear and based on the current pool sizes, but as mentioned earlier, it includes a slight tweak for security (the offset).</p><p>The <strong>common formulas</strong> used (in pseudo-code) are as follows:</p><ul><li>To calculate shares from a deposit of assets:</li></ul><pre>shares = assets * (total_supply + 10^decimals_offset) / (total_assets + 1)</pre><ul><li>To calculate assets that can be withdrawn for a given shares amount:</li></ul><pre>assets = shares * (total_assets + 1) / (total_supply + 10^decimals_offset)</pre><p>Here, total_supply and total_assets are the values <em>before</em> the deposit or withdrawal (i.e., current state), and 10^decimals_offset and 1 are the virtual share and asset added to protect against the empty vault scenario. The decimals_offset raises 10 to that power (effectively a scaling factor for initial shares). The +1 on assets is similarly a tiny virtual asset to prevent division by zero.</p><p>The multiplication and division should be done in high precision. In the standard implementation, the library provides a muldiv utility that multiplies then divides safely in one operation to avoid overflow and to handle rounding. Typically:</p><ul><li>Depositing (converting assets to shares) is done with downward rounding (floor) so that users might get slightly fewer shares if there’s a fraction, ensuring no extra shares are accidentally minted.</li><li>Withdrawing (converting shares to assets) might be rounded up (in favor of the user) or down, depending on design, but the standard should stick to a consistent rounding direction for predictability.</li></ul><p><strong>Example:</strong> Suppose the vault is empty and has offset = 2. So, 10^decimals_offset = 10^2 = 100. Initially, total_supply = 0 and total_assets = 0. If a user deposits 50 assets into the empty vault:</p><pre>shares = 50 * (0 + 100) / (0 + 1) = 50 * 100 / 1 = 5000 shares</pre><p>The user gets 5,000 vault tokens for their 50 assets. The exchange rate at this moment is 50 assets / 5000 shares = 0.01 assets per share (or inversely 100 shares per asset). Notice how the first depositor got a large number of shares per asset due to the offset (this is by design). It means if an attacker donates assets after this, they won’t drastically reduce subsequent depositor’s share counts, and the attacker themselves would not benefit because their donation doesn’t give them new shares.</p><p>Now, if another user comes and deposits 50 assets more (with the vault now having total_assets ~ 50 and total_supply ~ 5000):</p><pre>shares = 50 * (5000 + 100) / (50 + 1) ≈ 50 * 5100 / 51 ≈ 50 * 100 = 5000 shares</pre><p>This second user also gets about 5000 shares for 50 assets. After their deposit, the vault has ~100 assets and ~10000 shares in total. The exchange rate is about 0.01 assets/share (or 100 shares/asset). As yield accrues or assets are added/removed, total_assets/total_supply will change, which these formulas account for.</p><p>The key point is that when the vault was empty, the math ensured the first depositor got a fair (even generous) amount of shares so that no one can ever cause a situation where a depositor gets 0 shares. Without the offset, the first depositor in an empty vault would set total_supply and total_assets directly and an attacker could exploit that moment with a donation. The offset creates a buffer that makes such donation attacks ineffective.</p><p>In implementation, you typically don’t need to write these formulas yourself, the standard vault library should handle it. But it’s important to understand how your shares and assets are computed to avoid surprises.</p><h4>Building and Deploying a Soroban Vault (Step-by-Step)</h4><p>Now that we understand the concept and functions of a tokenized vault, let’s walk through creating a simple vault smart contract on the Stellar Soroban platform. We will use OpenZeppelin’s packages/crates which provides the standard vault logic, so we can focus on wiring it up and not re-implement everything from scratch.</p><p><a href="https://developers.stellar.org/docs/tools/openzeppelin-contracts">https://developers.stellar.org/docs/tools/openzeppelin-contracts</a></p><p><strong>Prerequisites:</strong> Before starting, make sure you have the following set up:</p><ul><li><strong>Rust</strong> (recommended version 1.90 or later).</li><li><strong>Stellar CLI</strong> (recommended version 23.0 or later).</li><li>The <strong>Rust target</strong> for wasm32v1-none installed.</li><li>A funded Stellar <strong>testnet account</strong> and wallet to deploy and interact with the contract (you can get test XLM from the Stellar <a href="https://lab.stellar.org/account/fund">Friendbot faucet</a>).</li></ul><h4>Step 1: Initialize a New Soroban Project</h4><p>Use the Stellar CLI tool to create a new Soroban smart contract project. Open a terminal and run:</p><pre>stellar contract init simple-vault</pre><p>This will create a new directory simple-vault with a template Soroban project (by default it will be a &quot;hello world&quot; contract template).</p><p>Change into the project directory:</p><pre>cd simple-vault</pre><p>You can open this project in your code editor for easier editing.</p><h4>Step 2: Add OpenZeppelin Dependencies</h4><p>Open the root <strong>Cargo.toml</strong> file. We need to add OpenZeppelin’s Stellar packages to our workspace dependencies. Under the [workspace.dependencies] section, add the following (assuming the latest release candidate at the time of writing):</p><pre>[workspace.dependencies]<br>soroban-sdk = &quot;23.0.2&quot;<br>stellar-tokens = { git = &quot;https://github.com/OpenZeppelin/stellar-contracts&quot;, tag = &quot;v0.5.0-rc.3&quot; }<br>stellar-access = { git = &quot;https://github.com/OpenZeppelin/stellar-contracts&quot;, tag = &quot;v0.5.0-rc.3&quot; }<br>stellar-contract-utils = { git = &quot;https://github.com/OpenZeppelin/stellar-contracts&quot;, tag = &quot;v0.5.0-rc.3&quot; }<br>stellar-macros = { git = &quot;https://github.com/OpenZeppelin/stellar-contracts&quot;, tag = &quot;v0.5.0-rc.3&quot; }</pre><p>These bring in the token contracts (including vault), access control, utilities, and macros from OpenZeppelin for Soroban.</p><p>Next, open the <strong>Cargo.toml</strong> inside simple-vault/contracts/hello-world/). In that file:</p><ul><li>Change the package name (e.g., from “hello-world” to “vault”).</li><li>Add the dependencies to the [dependencies] section, referencing the workspace packages:</li></ul><pre>[dependencies]<br>soroban-sdk = { workspace = true }<br>stellar-tokens = { workspace = true }<br>stellar-access = { workspace = true }<br>stellar-contract-utils = { workspace = true }<br>stellar-macros = { workspace = true }</pre><p>This makes the contract use the same versions of the OZ libraries defined in the workspace.</p><h4>Step 3: Write the Vault Contract Code</h4><p>Now let’s write our contract. In the src/ directory, you likely have a lib.rs from the template. We can simplify the structure by deleting the default test.rs (we won&#39;t cover tests here, though in a real project you should). Then delete the existing code in lib.rs and update to include our contract module:</p><p><strong>lib.rs:</strong></p><pre>#![no_std]<br>#![allow(dead_code)]<br><br>mod contract;</pre><p>This just sets up a contract module (which we&#39;ll create next) and applies some attributes.</p><p>Create a new file contract.rs in the src/ directory and add the following code:</p><pre>use soroban_sdk::{contract, contractimpl, Address, Env, String};<br>use stellar_macros::default_impl;<br>use stellar_tokens::fungible::{<br>    vault::{FungibleVault, Vault},<br>    Base, FungibleToken,<br>};<br><br>#[contract]<br>pub struct VaultExampleContract;<br><br>#[contractimpl]<br>impl VaultExampleContract {<br>    // Constructor to initialize the vault<br>    pub fn __constructor(e: &amp;Env, asset: Address, decimals_offset: u32) {<br>        // Set the underlying asset and the decimal offset once, at initialization.<br>        Vault::set_asset(e, asset);<br>        Vault::set_decimals_offset(e, decimals_offset);<br>        // Initialize metadata (name, symbol, decimals) for the share token.<br>        // We call Self::decimals(e) to get underlying_decimals + offset.<br>        Base::set_metadata(<br>            e,<br>            Self::decimals(e),<br>            String::from_str(e, &quot;Vault Token&quot;),<br>            String::from_str(e, &quot;VLT&quot;),<br>        );<br>    }<br>}<br><br>#[default_impl]<br>#[contractimpl]<br>impl FungibleToken for VaultExampleContract {<br>    type ContractType = Vault;<br><br>    // Override the decimals function (demonstration).<br>    fn decimals(e: &amp;Env) -&gt; u32 {<br>        Vault::decimals(e)<br>    }<br><br>    // We could override other Base token functions if needed, but by default<br>    // default_impl macro will use the default implementations.<br>}<br><br>#[contractimpl]<br>impl FungibleVault for VaultExampleContract {<br>    // We delegate each vault-specific function to the standard Vault implementation.<br>    fn query_asset(e: &amp;Env) -&gt; Address {<br>        Vault::query_asset(e)<br>    }<br><br>    fn total_assets(e: &amp;Env) -&gt; i128 {<br>        Vault::total_assets(e)<br>    }<br><br>    fn convert_to_shares(e: &amp;Env, assets: i128) -&gt; i128 {<br>        Vault::convert_to_shares(e, assets)<br>    }<br><br>    fn convert_to_assets(e: &amp;Env, shares: i128) -&gt; i128 {<br>        Vault::convert_to_assets(e, shares)<br>    }<br>    fn max_deposit(e: &amp;Env, receiver: Address) -&gt; i128 {<br>        Vault::max_deposit(e, receiver)<br>    }<br><br>    fn preview_deposit(e: &amp;Env, assets: i128) -&gt; i128 {<br>        Vault::preview_deposit(e, assets)<br>    }<br><br>    fn max_mint(e: &amp;Env, receiver: Address) -&gt; i128 {<br>        Vault::max_mint(e, receiver)<br>    }<br><br>    fn preview_mint(e: &amp;Env, shares: i128) -&gt; i128 {<br>        Vault::preview_mint(e, shares)<br>    }<br><br>    fn max_withdraw(e: &amp;Env, owner: Address) -&gt; i128 {<br>        Vault::max_withdraw(e, owner)<br>    }<br><br>    fn preview_withdraw(e: &amp;Env, assets: i128) -&gt; i128 {<br>        Vault::preview_withdraw(e, assets)<br>    }<br><br>    fn max_redeem(e: &amp;Env, owner: Address) -&gt; i128 {<br>        Vault::max_redeem(e, owner)<br>    }<br><br>    fn preview_redeem(e: &amp;Env, shares: i128) -&gt; i128 {<br>        Vault::preview_redeem(e, shares)<br>    }<br><br>    fn deposit(e: &amp;Env, assets: i128, receiver: Address, from: Address, operator: Address) -&gt; i128 {<br>        operator.require_auth();<br>        Vault::deposit(e, assets, receiver, from, operator)<br>    }<br><br>    fn mint(e: &amp;Env, shares: i128, receiver: Address, from: Address, operator: Address) -&gt; i128 {<br>        operator.require_auth();<br>        Vault::mint(e, shares, receiver, from, operator)<br>    }<br><br>    fn withdraw(<br>        e: &amp;Env,<br>        assets: i128,<br>        receiver: Address,<br>        owner: Address,<br>        operator: Address,<br>    ) -&gt; i128 {<br>        operator.require_auth();<br>        Vault::withdraw(e, assets, receiver, owner, operator)<br>    }<br><br>    fn redeem(e: &amp;Env, shares: i128, receiver: Address, owner: Address, operator: Address) -&gt; i128 {<br>        operator.require_auth();<br>        Vault::redeem(e, shares, receiver, owner, operator)<br>    }<br>}</pre><p>Let’s break down what this code is doing:</p><ul><li>We import the necessary modules from Soroban SDK and OpenZeppelin’s packages. Vault is the struct that implements the vault logic, and FungibleVault is a trait with all the vault function definitions.</li><li>In the impl VaultExampleContract section, we have a special __constructor function. This will run once when the contract is initialized. It takes the asset (an Address of the underlying token contract) and a decimals_offset (a u32). Inside, we call:</li><li>Vault::set_asset(e, asset) – this stores the underlying asset address in the contract’s storage.</li><li>Vault::set_decimals_offset(e, decimals_offset) – stores the virtual decimals offset. <strong>Important:</strong> we do this before setting metadata.</li><li>We then call Base::set_metadata to set the share token’s decimals, name, and symbol. We fetch the decimals via Self::decimals(e) which we override to call Vault::decimals(e). The vault’s decimals function will calculate underlying_decimals + offset for us. In this example, we name the token &quot;Vault Token&quot; (symbol &quot;VLT&quot;), but you can choose any name/symbol appropriate.</li><li>Next, we implement the FungibleToken (SEP-41 compliant) trait for our contract with #[default_impl]. This macro means if we don’t override a function, it will use the default implementation. For demonstration purposes, we override the decimals function.</li><li>Finally, we implement the FungibleVault trait for our contract. This trait includes all the ERC-4626 style functions we enumerated earlier. We simply forward each call to Vault::function(...) to reuse the standard implementation. For the state-changing functions (deposit, mint, withdraw, redeem) we also add operator.require_auth() which ensures the transaction is authorized by the operator address (usually the caller) before proceeding. By design, the OpenZeppelin library delegates this decision to us, the implementers.</li></ul><p>In essence, our contract code is a thin wrapper that initializes the vault parameters and delegates all functionality to the well-tested OpenZeppelin Vault logic. This demonstrates the power of using the library – we wrote very little custom code.</p><blockquote><strong>Note:</strong> The OpenZeppelin library assumes the implementers are responsible for certain maintenance tasks, like bumping the instance storage expiration (rent) if needed and handling authorization properly. In a real deployment, ensure you manage the storage’s lifetime and have the necessary authorization flows.</blockquote><h4>Step 4: Build and Optimize the Contract</h4><p>Now compile the contract into WebAssembly (WASM). From the project directory, run:</p><pre>stellar contract build</pre><p>This will compile the Rust code into a WASM file (in release mode by default, targeting <em>wasm32v1-none</em>). To optimize the contract, run:</p><pre>stellar contract optimize --wasm target/wasm32v1-none/release/vault.wasm</pre><p>The optimize command takes the compiled WASM (vault.wasm) and optimizes it, outputting vault.optimized.wasm. This optimized WASM is what we’ll deploy.</p><h4>Step 5: Deploy the Vault on Stellar Testnet</h4><p>With the optimized contract ready, we can deploy it to the Stellar testnet. We need to provide the constructor arguments at deploy time: the underlying asset address and the decimals offset.</p><p>For testing, we can use Stellar’s native <strong>Testnet XLM</strong> as the underlying asset. On Soroban, it is represented by a token contract address. The testnet asset contract address for XLM:CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQVU2HHGCYSC (or you can use your own asset contract). We&#39;ll use decimals offset = 0 for simplicity in this example (though in production you would choose a non-zero offset for security as discussed).</p><p>Run the deploy command (replace --source-account value with your testnet account, such as <em>alice </em>or <em>bob</em>):</p><pre>stellar contract deploy \<br> --wasm target/wasm32v1-none/release/vault.optimized.wasm \<br> --source-account &lt;YOUR_TESTNET_ACCOUNT&gt; \<br> --network testnet \<br> --alias vault \<br> -- \<br> --asset CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQVU2HHGCYSC \<br> --decimals_offset 0</pre><p>Breaking that down:</p><ul><li>--source-account is your testnet account (funded with XLM) that will pay the deployment fee and be the contract initializer.</li><li>--alias vault just gives a local name &quot;vault&quot; to refer to this contract in CLI.</li><li>After the -- we pass the constructor arguments: --asset followed by the underlying asset ID, and --decimals_offset followed by the offset value.</li></ul><p>If successful, the CLI will output a confirmation:</p><pre>🌎 Submitting deploy transaction…<br>🔗 https://stellar.expert/explorer/testnet/contract/&lt;CONTRACT_ID&gt;...<br>✅ Deployed!<br>&lt;CONTRACT_ID&gt;</pre><p>Copy down the &lt;CONTRACT_ID&gt; which is the address of your new vault contract.</p><h4>Step 6: Testing the Vault Functions</h4><p>Now that our vault is deployed, let’s test it out! We can use the <strong>Stellar Laboratory </strong>or the Soroban CLI to invoke the contract functions. For this tutorial, we’ll use Stellar Lab’s contract explorer:</p><p><a href="https://lab.stellar.org/smart-contracts/contract-explorer">https://lab.stellar.org/smart-contracts/contract-explorer</a></p><ol><li>Go to the Stellar Laboratory smart contracts explorer (make sure it’s on testnet). Then input your vault contract ID: <em>Stellar Lab &gt; Smart Contracts &gt; Contract Explorer</em>.</li><li>Click to load it. You should see the contract details and specifications. Switch to the “<em>Invoke Contract</em>“ tab, and connect your Stellar wallet.</li><li>Try calling some read-only functions first. For example, find the decimals function. Click “<em>Simulate</em>” – it should return 7 if you used testnet XLM with offset 0 (XLM has 7 decimals). If you used a different asset or offset, it will return underlying decimals + offset.</li><li>Now let’s <strong>deposit</strong> some assets. In Stellar Lab:</li></ol><ul><li>Find the deposit function.</li><li>For assets, input an amount in the base units of the token. For example, to deposit 10 XLM, since XLM has 7 decimals, enter 100000000 (which is 10 * 10^7).</li><li>For receiver, put your own account address (public key) – you want the shares to come to you.</li><li>For from and operator, also use your account address.</li><li>Click “<em>Simulate</em>”. Once you simulate, you should see the JSON result, containing the number of shares returned (if offset was 0, it should be 10 XLM worth of shares, which might also be 100000000 shares because 1:1 in this scenario).</li><li>If all looks good, click “<em>Simulate &amp; Submit</em>” to actually submit the transaction. Approve the transaction with your wallet. After submission, your account should now have 10 fewer XLM, and the vault contract holds those 10 XLM.</li></ul><p>5. Check the state:</p><ul><li>After deposit, you can simulate total_assets via Lab – it should show 100000000 (which is 10 XLM in stroops) now held by the vault.</li><li>total_supply (of the vault token) should also show 100000000 (10 vault shares) since you are the only depositor.</li><li>balance for your address on the vault contract should show 100000000 shares as well.</li></ul><p>6. Try a <strong>withdrawal</strong>. Use the withdraw function:</p><ul><li>For assets, enter 50000000 (which is 5 XLM, half of what you deposited, in stroops).</li><li>For receiver, use your account (you want to receive the XLM back).</li><li>For owner, use your account.</li><li>For operator, use your account as well.</li><li>Simulate the transaction. It should succeed and indicate ~5 XLM worth will be withdrawn (burning the equivalent shares, which should be 50000000 shares if 1:1).</li><li>Submit the transaction. Afterward, you should see ~5 XLM returned to your account (your XLM balance increases by 5, minus network fees).</li><li>The vault now should have 5 XLM remaining (total_assets ~ 50,000,000 stroops) and total_supply ~ 50,000,000 (since half the shares were burned). Because you were the only participant, these numbers align with your remaining stake.</li></ul><p>7. You can also test max_withdraw (putting your address as owner) which should now return 50000000 (the max assets you can still withdraw, which is 5 XLM remaining). Similarly, max_redeem for your address should return 50000000 shares.</p><p>8. Feel free to experiment with the other functions:</p><ul><li>Use preview_deposit or preview_mint to see the calculations without actually doing them.</li><li>Try mint by specifying a number of shares to mint.</li><li>If you have another test accounts, try depositing on their behalf by setting receiver to their address while you are the from/operator. The shares will go to them, but you supply the assets.</li></ul><blockquote>For operations where owner/from and operator addresses differ, ensure that token allowances are handled beforehand.</blockquote><p>Throughout these operations, monitor both the contract storage and the emitted events. You should see the Deposit event for your deposit and a Withdraw event for the withdrawal.</p><p><strong>Congratulations, you now have a functioning vault on Soroban!</strong></p><h4>Ideas for Extensions and Real-World Applications</h4><p>The simple vault we deployed doesn’t actually do anything with the assets except hold them. In a real DeFi scenario, the vault would integrate with strategies or other protocols to generate yield (that yield would reflect as an increase in total_assets without minting new shares, thus increasing each share’s value). Here are a few ideas on how you could extend or use a tokenized vault:</p><ul><li><strong>Yield Aggregator:</strong> The vault could deposit the underlying assets into various Stellar ecosystem yield sources to earn rewards. The contract could automatically compound earnings.</li><li><strong>Lending/Borrowing Vault:</strong> The vault could represent a lending pool. Users deposit an asset and receive vault tokens, and the vault contract lends out the asset to borrowers (e.g., via another contract) earning interest. Vault share tokens here represent a claim on the lending pool.</li><li><strong>Interest-Bearing Stablecoins:</strong> You could issue a stablecoin that is intrinsically yield-bearing by backing it with a vault. For example, users deposit USDC into the vault, which invests it, and they get back a token that slowly increases in value or quantity, effectively creating a savings account token.</li><li><strong>Fee Capture Strategies:</strong> You might modify the vault to take a small fee on each deposit or each yield harvest (similar to performance or management fees in funds). The fee could be sent to a treasury or elsewhere, depending on the model.</li><li><strong>Time-locked Vaults:</strong> Add features to restrict withdrawals for a period (maybe for a fixed-term vault or a bond-like instrument). The vault could enforce that shares cannot be redeemed until a certain time or without a penalty.</li><li><strong>Multi-Asset Vaults / LP Vaults:</strong> Standard tokenized vault (ERC-4626) is for single assets, but you could have a vault that accepts and manages multiple assets (though there are other standards for multi-asset vaults).</li><li><strong>Prediction Markets:</strong> Vaults don’t have to just earn yield, they could pool funds for a common purpose. For example, a prediction market might use a vault to pool stake on an event, where share tokens represent a claim that will later be redeemable based on the outcome.</li></ul><p>These are just a few possibilities. The vault pattern provides a flexible way to tokenize pooled resources, so you can get creative with it.</p><h4>Conclusion and Next Steps</h4><p>In this tutorial, we covered the concept of tokenized vaults and implemented an ERC-4626-style vault on Stellar Soroban using OpenZeppelin’s library. We discussed how vaults work, their key functions and events, and the importance of standards like ERC-4626 for interoperability and security. We also went through deploying a vault and interacting with it on testnet, and considered some extensions for real-world applications.</p><p>From here, you can start building your own custom vault logic on top of this foundation. For instance, you could integrate calls to other contracts in the deposit/withdraw flows to implement a yield strategy, or add admin controls for pausing deposits, etc. Always remember to thoroughly test your vault and be mindful of Soroban-specific aspects like rent (storage expiration) and auth scopes.</p><p>We hope this guide has demystified tokenized vaults on Soroban and shown that with the right tools, it’s straightforward to get started. If you have questions or feedback, feel free to reach out through the <a href="https://stellar.org/community">Stellar developer community</a> channels.</p><p>Happy building!</p><blockquote>Written by the Sentinel team.</blockquote><h4>Further Reading</h4><ul><li><a href="https://docs.openzeppelin.com/stellar-contracts">https://docs.openzeppelin.com/stellar-contracts</a></li><li><a href="https://github.com/OpenZeppelin/stellar-contracts">https://github.com/OpenZeppelin/stellar-contracts</a></li><li><a href="https://docs.openzeppelin.com/contracts/5.x/erc4626">https://docs.openzeppelin.com/contracts/5.x/erc4626</a></li><li><a href="https://eips.ethereum.org/EIPS/eip-4626">https://eips.ethereum.org/EIPS/eip-4626</a></li><li><a href="https://ethereum.org/developers/docs/standards/tokens/erc-4626/">https://ethereum.org/developers/docs/standards/tokens/erc-4626/</a></li><li><a href="https://erc4626.info/">https://erc4626.info/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33a7cda08649" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>