Install WebAssembly (Wasm) bytecode using code
This process uploads the contract code to the Stellar Testnet in a transaction, the uploaded Wasm blob is a contract source, which can be thought of as a ‘class’ of a contract. Multiple instances of a contract can be deployed which share the same source, but have their own state.Prerequisites
Before you begin, ensure you have the following installed to compile a smart contract:- Rust and Cargo (for compiling smart contracts)
- The Stellar CLI
Initialize and build a sample Rust contract
stellar contract init hello-world
cd hello-world
# use rust compiler to compile Rust project into a WebAssembly (Wasm) dynamic library (cdylib).
stellar contract build
# cargo rustc --manifest-path=contracts/hello_world/Cargo.toml --crate-type=cdylib --target=wasm32v1-none --release
hello_world contract in soroban_examples to the directory hello-world. You may use the -w option to create with another example like account.
After building the contract for release, the generated .wasm file is at the path hello-word/target/wasm32v1-none/release/hello_world.wasm
Upload Wasm to the Stellar blockchain
We can use one of the client SDKs, install necessary dependencies for your chosen programming language:- JavaScript SDK: Node.js and npm
- Python SDK: pip
- Go SDK: Go
- Java SDK: Java 17 or later and Maven
mkdir install-wasm
cd install-wasm
Running the install script
Different programming languages can be used to upload the.wasm file, its SHA256 hash is used for deploying the contract.
- JavaScript
- Python
- Go
- Java
- Rust
This guide will walk you through installing the Wasm of the contract using the JavaScript SDK: js-stellar-sdk.Create a new Node.js project with a JavaScript file, and install necessary dependencies:Run the script with
touch index.js
npm init es6 -y
npm install @stellar/stellar-sdk fs
node index.js, it reads the Wasm file, gets account details, and uploads the contract in a transaction:// Import necessary modules in your JavaScript file:
import * as StellarSDK from "@stellar/stellar-sdk";
import fs from "fs";
async function uploadWasm(filePath) {
// reads the compiled Wasm file to buffer
const bytecode = fs.readFileSync(filePath);
// retrieves account details from the network
const account = await server.getAccount(sourceKeypair.publicKey());
// installs the bytecode with a `uploadContractWasm` Stellar operation wrapped in a transaction sent to the network
const operation = StellarSDK.Operation.uploadContractWasm({ wasm: bytecode });
return await buildAndSendTransaction(account, operation);
}
// constructs a transaction, signs it, and submits it to the network, handling any necessary retries for transaction confirmation.
async function buildAndSendTransaction(account, operations) {
// Bid what recent transactions paid, capped at what you're willing to spend.
// prepareTransaction adds the resource fee on top of this inclusion fee.
const { sorobanInclusionFee } = await server.getFeeStats();
const MAX_FEE = 100_000; // stroops per operation (0.01 XLM): pick your own cap
const fee = String(Math.min(Number(sorobanInclusionFee.p90), MAX_FEE));
const transaction = new StellarSDK.TransactionBuilder(account, {
fee,
networkPassphrase: StellarSDK.Networks.TESTNET,
})
.addOperation(operations)
.setTimeout(30)
.build();
const tx = await server.prepareTransaction(transaction);
tx.sign(sourceKeypair);
console.log("Submitting transaction...");
const sendResponse = await server.sendTransaction(tx);
console.log(`Transaction hash: ${sendResponse.hash}`);
// PENDING and DUPLICATE mean the network has the transaction.
// TRY_AGAIN_LATER and ERROR mean the network did not accept it.
if (
sendResponse.status === "TRY_AGAIN_LATER" ||
sendResponse.status === "ERROR"
) {
throw new Error(`Transaction not accepted: ${sendResponse.status}`);
}
console.log("Awaiting confirmation...");
// Poll getTransaction once a second, for up to 30 attempts
const response = await server.pollTransaction(sendResponse.hash, {
attempts: 30,
});
// NOT_FOUND after the last attempt means the result is unknown,
// not that the transaction failed
if (response.status === "NOT_FOUND") {
throw new Error("Not confirmed yet. Check again before resending.");
}
if (response.status === "SUCCESS") {
console.log("Transaction successful.");
return response;
} else {
console.log("Transaction failed.");
throw new Error(`Transaction did not succeed: ${response.status}`);
}
}
// Upload contract to the testnet
const server = new StellarSDK.rpc.Server(
"https://soroban-testnet.stellar.org:443",
);
// Replace `Your_Secret_Key`
const sourceKeypair = StellarSDK.Keypair.fromSecret("Your_Secret_Key");
// Adjust this path as necessary
const wasmFilePath = "../target/wasm32v1-none/release/hello_world.wasm";
try {
let uploadResponse = await uploadWasm(wasmFilePath);
const byteArray = StellarSDK.scValToNative(uploadResponse.returnValue);
const wasmHash = Buffer.from(byteArray).toString("hex");
console.log(`Wasm hash: ${wasmHash}`);
} catch (error) {
console.error(error);
}
This guide will walk you through installing the Wasm of the contract using the Python SDK: py-stellar-base.Create a new Python script, and install the necessary dependencies:Run the script with
touch install.py
pip install stellar-sdk
python3 install.py, it reads the Wasm file, gets account details, and uploads the contract in a transaction:import asyncio
from stellar_sdk import Keypair, Network, SorobanServer, TransactionBuilder, xdr as stellar_xdr
from stellar_sdk.exceptions import PrepareTransactionException
from stellar_sdk.soroban_rpc import GetTransactionStatus, SendTransactionStatus
import hashlib
def print_wasm_hash(wasm_bytes):
# Create a SHA256 hash object
sha256_hash = hashlib.sha256()
# Update the hash object with the WASM bytes
sha256_hash.update(wasm_bytes)
# Get the digest and convert it to a stellar_sdk.xdr.Hash object
hash_bytes = sha256_hash.digest()
xdr_hash = stellar_xdr.Hash(hash_bytes)
hash_hex_str = xdr_hash.hash.hex()
print(f"Wasm Hash: {hash_hex_str}")
async def upload_wasm(file_path):
# Read the compiled Wasm file
with open(file_path, 'rb') as file:
wasm_bytes = file.read()
# Retrieve account details from the network
account = server.load_account(source_keypair.public_key)
# print wasm hash for later deployment
print_wasm_hash(wasm_bytes)
# Install the bytes with an 'uploadContractWasm' Stellar operation
return await build_and_send_transaction(account, wasm_bytes)
async def build_and_send_transaction(account, bytes):
# Bid what recent transactions paid, capped at what you're willing to spend.
# Without base_fee, the builder bids 100 stroops, the network minimum.
# prepare_transaction adds the resource fee on top of this inclusion fee.
MAX_FEE = 100_000 # stroops per operation (0.01 XLM): pick your own cap
fee = min(server.get_fee_stats().soroban_inclusion_fee.p90, MAX_FEE)
transaction = (
TransactionBuilder(
source_account=account,
network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
base_fee=fee,
)
.append_upload_contract_wasm_op(bytes)
.set_timeout(30)
.build()
)
print("Preparing transaction...")
try:
tx = server.prepare_transaction(transaction)
except PrepareTransactionException as e:
print(f"Got exception: {e}")
return None
tx.sign(source_keypair)
print("Submitting transaction...")
send_response = server.send_transaction(tx)
print(f"Transaction hash: {send_response.hash}")
# PENDING and DUPLICATE mean the network has the transaction.
# TRY_AGAIN_LATER and ERROR mean the network did not accept it.
if send_response.status in (
SendTransactionStatus.TRY_AGAIN_LATER,
SendTransactionStatus.ERROR,
):
raise Exception(f"Transaction not accepted: {send_response.status.value}")
print("Awaiting confirmation...")
# Poll get_transaction once a second, for up to 30 attempts
response = server.poll_transaction(send_response.hash, max_attempts=30)
# NOT_FOUND after the last attempt means the result is unknown,
# not that the transaction failed
if response.status == GetTransactionStatus.NOT_FOUND:
raise Exception("Not confirmed yet. Check again before resending.")
if response.status == GetTransactionStatus.SUCCESS:
print("Transaction successful.")
return response
else:
print("Transaction failed.")
raise Exception(f"Transaction did not succeed: {response.status.value}")
# Upload contract to the testnet
server = SorobanServer("https://soroban-testnet.stellar.org:443")
# Replace 'Your_Secret_Key' with your actual secret key
source_keypair = Keypair.from_secret("Your_Secret_Key")
# Adjust this path as necessary
wasm_file_path = "../target/wasm32v1-none/release/hello_world.wasm"
async def main():
try:
await upload_wasm(wasm_file_path)
except Exception as error:
print(f"Error: {error}")
# Run the main function
asyncio.run(main())
This guide will walk you through installing the Wasm of the contract using the Go SDK: go-stellar-sdk.Create a new Go module, and install the necessary dependencies:Copy the code below into
go mod init install-wasm
go get github.com/stellar/go-stellar-sdk
main.go, then run it with go run main.go. It reads the Wasm file, gets account details, and uploads the contract in a transaction:package main
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"log"
"os"
"time"
"github.com/stellar/go-stellar-sdk/keypair"
"github.com/stellar/go-stellar-sdk/network"
"github.com/stellar/go-stellar-sdk/txnbuild"
"github.com/stellar/go-stellar-sdk/xdr"
client "github.com/stellar/go-stellar-sdk/clients/rpcclient"
protocol "github.com/stellar/go-stellar-sdk/protocols/rpc"
)
// Upload contract to the testnet
var server = client.NewClient("https://soroban-testnet.stellar.org:443", nil)
// Replace `Your_Secret_Key`
var sourceKeypair = keypair.MustParseFull("Your_Secret_Key")
// Adjust this path as necessary
const wasmFilePath = "../target/wasm32v1-none/release/hello_world.wasm"
func main() {
if err := uploadWasm(context.Background(), wasmFilePath); err != nil {
log.Fatal(err)
}
}
func uploadWasm(ctx context.Context, filePath string) error {
// reads the compiled Wasm file
bytecode, err := os.ReadFile(filePath)
if err != nil {
return err
}
// retrieves account details from the network
account, err := server.LoadAccount(ctx, sourceKeypair.Address())
if err != nil {
return err
}
// installs the bytecode with an `UploadContractWasm` host function wrapped in a transaction sent to the network
operation := &txnbuild.InvokeHostFunction{
HostFunction: xdr.HostFunction{
Type: xdr.HostFunctionTypeHostFunctionTypeUploadContractWasm,
Wasm: &bytecode,
},
SourceAccount: sourceKeypair.Address(),
}
if _, err := buildAndSendTransaction(ctx, account, operation); err != nil {
return err
}
// The Wasm hash is the SHA-256 hash of the bytecode
wasmHash := sha256.Sum256(bytecode)
fmt.Printf("Wasm hash: %s\n", hex.EncodeToString(wasmHash[:]))
return nil
}
// constructs a transaction, signs it, and submits it to the network, handling any necessary retries for transaction confirmation.
func buildAndSendTransaction(
ctx context.Context,
account txnbuild.Account,
operation *txnbuild.InvokeHostFunction,
) (protocol.GetTransactionResponse, error) {
var none protocol.GetTransactionResponse
// Bid what recent transactions paid, capped at what you're willing to spend.
// prepareTransaction adds the resource fee on top of this inclusion fee.
feeStats, err := server.GetFeeStats(ctx)
if err != nil {
return none, err
}
const maxFee = 100_000 // stroops per operation (0.01 XLM): pick your own cap
fee := min(int64(feeStats.SorobanInclusionFee.P90), maxFee)
tx, err := prepareTransaction(ctx, txnbuild.TransactionParams{
SourceAccount: account,
IncrementSequenceNum: true,
BaseFee: fee,
Preconditions: txnbuild.Preconditions{TimeBounds: txnbuild.NewTimeout(30)},
Operations: []txnbuild.Operation{operation},
})
if err != nil {
return none, err
}
tx, err = tx.Sign(network.TestNetworkPassphrase, sourceKeypair)
if err != nil {
return none, err
}
envelope, err := tx.Base64()
if err != nil {
return none, err
}
fmt.Println("Submitting transaction...")
sendResponse, err := server.SendTransaction(ctx, protocol.SendTransactionRequest{Transaction: envelope})
if err != nil {
return none, err
}
fmt.Printf("Transaction hash: %s\n", sendResponse.Hash)
// PENDING and DUPLICATE mean the network has the transaction.
// TRY_AGAIN_LATER and ERROR mean the network did not accept it.
if sendResponse.Status == "TRY_AGAIN_LATER" || sendResponse.Status == "ERROR" {
return none, fmt.Errorf("transaction not accepted: %s", sendResponse.Status)
}
fmt.Println("Awaiting confirmation...")
// Poll getTransaction once a second, for up to 30 attempts
var response protocol.GetTransactionResponse
for range 30 {
response, err = server.GetTransaction(ctx, protocol.GetTransactionRequest{Hash: sendResponse.Hash})
if err != nil {
return none, err
}
if response.Status != protocol.TransactionStatusNotFound {
break
}
time.Sleep(time.Second)
}
// NOT_FOUND after the last attempt means the result is unknown,
// not that the transaction failed
if response.Status == protocol.TransactionStatusNotFound {
return none, errors.New("not confirmed yet, check again before resending")
}
if response.Status == protocol.TransactionStatusSuccess {
fmt.Println("Transaction successful.")
return response, nil
}
fmt.Println("Transaction failed.")
return response, fmt.Errorf("transaction did not succeed: %s", response.Status)
}
// prepareTransaction simulates the transaction, then builds it again with the
// simulated resources, resource fee, and authorization entries.
func prepareTransaction(ctx context.Context, params txnbuild.TransactionParams) (*txnbuild.Transaction, error) {
tx, err := txnbuild.NewTransaction(params)
if err != nil {
return nil, err
}
envelope, err := tx.Base64()
if err != nil {
return nil, err
}
sim, err := server.SimulateTransaction(ctx, protocol.SimulateTransactionRequest{Transaction: envelope})
if err != nil {
return nil, err
}
if sim.Error != "" {
return nil, fmt.Errorf("simulation failed: %s", sim.Error)
}
var sorobanData xdr.SorobanTransactionData
if err := xdr.SafeUnmarshalBase64(sim.TransactionDataXDR, &sorobanData); err != nil {
return nil, err
}
operation := params.Operations[0].(*txnbuild.InvokeHostFunction)
operation.Ext = xdr.TransactionExt{V: 1, SorobanData: &sorobanData}
// Keep the operation's own auth entries; otherwise use the simulated ones.
if len(operation.Auth) == 0 && len(sim.Results) > 0 && sim.Results[0].AuthXDR != nil {
for _, entryXDR := range *sim.Results[0].AuthXDR {
var entry xdr.SorobanAuthorizationEntry
if err := xdr.SafeUnmarshalBase64(entryXDR, &entry); err != nil {
return nil, err
}
operation.Auth = append(operation.Auth, entry)
}
}
// Build again with the same sequence number.
source := tx.SourceAccount()
params.SourceAccount = &source
params.IncrementSequenceNum = false
return txnbuild.NewTransaction(params)
}
This guide will walk you through installing the Wasm of the contract using the Java SDK: java-stellar-sdk.Create a new Maven project, and add the SDK to the Copy the code below into
<dependencies> section of its pom.xml:<dependency>
<groupId>network.lightsail</groupId>
<artifactId>stellar-sdk</artifactId>
<version>6.0.0</version>
</dependency>
src/main/java/UploadWasm.java, then run its main method. It reads the Wasm file, gets account details, and uploads the contract in a transaction:import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.util.HexFormat;
import org.stellar.sdk.KeyPair;
import org.stellar.sdk.Network;
import org.stellar.sdk.SorobanServer;
import org.stellar.sdk.Transaction;
import org.stellar.sdk.TransactionBuilder;
import org.stellar.sdk.TransactionBuilderAccount;
import org.stellar.sdk.operations.InvokeHostFunctionOperation;
import org.stellar.sdk.responses.sorobanrpc.GetTransactionResponse;
import org.stellar.sdk.responses.sorobanrpc.GetTransactionResponse.GetTransactionStatus;
import org.stellar.sdk.responses.sorobanrpc.SendTransactionResponse;
import org.stellar.sdk.responses.sorobanrpc.SendTransactionResponse.SendTransactionStatus;
public final class UploadWasm {
// Upload contract to the testnet
private static final SorobanServer server = new SorobanServer("https://soroban-testnet.stellar.org:443");
// Replace `Your_Secret_Key`
private static final KeyPair sourceKeypair = KeyPair.fromSecretSeed("Your_Secret_Key");
// Adjust this path as necessary
private static final String wasmFilePath = "../target/wasm32v1-none/release/hello_world.wasm";
public static void main(String[] args) throws Exception {
uploadWasm(wasmFilePath);
}
private static void uploadWasm(String filePath) throws Exception {
// reads the compiled Wasm file
byte[] bytecode = Files.readAllBytes(Path.of(filePath));
// retrieves account details from the network
TransactionBuilderAccount account = server.getAccount(sourceKeypair.getAccountId());
// installs the bytecode with an `uploadContractWasm` host function wrapped in a transaction sent to the network
InvokeHostFunctionOperation operation =
InvokeHostFunctionOperation.uploadContractWasmOperationBuilder(bytecode).build();
buildAndSendTransaction(account, operation);
// The Wasm hash is the SHA-256 hash of the bytecode
byte[] wasmHash = MessageDigest.getInstance("SHA-256").digest(bytecode);
System.out.println("Wasm hash: " + HexFormat.of().formatHex(wasmHash));
}
// constructs a transaction, signs it, and submits it to the network, handling any necessary retries for transaction confirmation.
private static GetTransactionResponse buildAndSendTransaction(
TransactionBuilderAccount account, InvokeHostFunctionOperation operation)
throws InterruptedException {
// Bid what recent transactions paid, capped at what you're willing to spend.
// prepareTransaction adds the resource fee on top of this inclusion fee.
long maxFee = 100_000L; // stroops per operation (0.01 XLM): pick your own cap
long fee = Math.min(server.getFeeStats().getSorobanInclusionFee().getP90(), maxFee);
Transaction transaction = new TransactionBuilder(account, Network.TESTNET)
.setBaseFee(fee)
.addOperation(operation)
.setTimeout(30)
.build();
Transaction tx = server.prepareTransaction(transaction);
tx.sign(sourceKeypair);
System.out.println("Submitting transaction...");
SendTransactionResponse sendResponse = server.sendTransaction(tx);
System.out.println("Transaction hash: " + sendResponse.getHash());
// PENDING and DUPLICATE mean the network has the transaction.
// TRY_AGAIN_LATER and ERROR mean the network did not accept it.
if (sendResponse.getStatus() == SendTransactionStatus.TRY_AGAIN_LATER
|| sendResponse.getStatus() == SendTransactionStatus.ERROR) {
throw new IllegalStateException("Transaction not accepted: " + sendResponse.getStatus());
}
System.out.println("Awaiting confirmation...");
// Poll getTransaction once a second, for up to 30 attempts
GetTransactionResponse response =
server.pollTransaction(sendResponse.getHash(), 30, attempt -> 1_000L);
// NOT_FOUND after the last attempt means the result is unknown,
// not that the transaction failed
if (response.getStatus() == GetTransactionStatus.NOT_FOUND) {
throw new IllegalStateException("Not confirmed yet. Check again before resending.");
}
if (response.getStatus() == GetTransactionStatus.SUCCESS) {
System.out.println("Transaction successful.");
return response;
}
System.out.println("Transaction failed.");
throw new IllegalStateException("Transaction did not succeed: " + response.getStatus());
}
}
This guide will walk you through uploading the Wasm of the contract using the Rust SDK: rs-soroban-client.Create a new Cargo project, and install the necessary dependencies:Copy the code below into
cargo init
cargo add soroban_client
cargo add tokio -F macros,full
src/main.rs then run the program with cargo run, it reads the Wasm file, gets account details, and uploads the contract in a transaction:use std::time::Duration;
use soroban_client::{
account::{Account, AccountBehavior},
keypair::{Keypair, KeypairBehavior},
network::{NetworkPassphrase, Networks},
operation::Operation,
soroban_rpc::TransactionStatus,
transaction::{TransactionBehavior, TransactionBuilder, TransactionBuilderBehavior},
Options, Server,
};
#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
let server_url = "https://soroban-testnet.stellar.org";
let server = Server::new(server_url, Options::default())?;
// Adjust this path as necessary
let wasm_file_path = "../target/wasm32v1-none/release/hello_world.wasm";
// Read the wasm file
let wasm_bytes = std::fs::read(wasm_file_path)?;
// Build the xdr::HostFunction::UploadContractWasm operation
let upload_wasm_op = Operation::new()
.upload_wasm(&wasm_bytes, None)
.expect("Cannot create upload_wasm operation");
// Replace Your_Secret_Key with your actual secret key
let source_keypair = Keypair::from_secret("Your_Secret_Key")?;
let source_public_key = &source_keypair.public_key();
// Get account information from server
let account_data = server.get_account(source_public_key).await?;
// Build the Account to use in the transaction
let mut source_account = Account::new(source_public_key, &account_data.sequence_number())?;
// Build the operation
let tx = TransactionBuilder::new(&mut source_account, Networks::testnet(), None)
.fee(1000u32)
.add_operation(upload_wasm_op)
.build();
let mut ptx = server.prepare_transaction(&tx).await?;
ptx.sign(&[source_keypair]);
println!("> Uploading WASM executable");
let response = server.send_transaction(ptx).await?;
let hash = &response.hash;
println!(">> Tx hash: {hash}");
let wasm_hash = match server.wait_transaction(hash, Duration::from_secs(15)).await {
Ok(tx_result) if tx_result.status == TransactionStatus::Success => {
let (_meta, ret_val) = tx_result.to_result_meta().expect("No meta found");
if let Some(scval) = ret_val {
let bytes: Vec<u8> = scval.try_into().expect("Cannot convert ScVal to Vec<u8>");
*bytes.last_chunk::<32>().expect("Not 32 bytes")
} else {
return Err(">> None return value".into());
}
}
_ => {
println!(">> Failed to upload the WASM executable");
return Err(">> Failed to upload the wasm".into());
}
};
let hex_wasm_hash: String = wasm_hash.iter().map(|b| format!("{:02x}", b)).collect();
println!(">> Wasm hash: {hex_wasm_hash}");
println!();
Ok(())
}
"Your_Secret_Key" with your actual secret key.
stellar keys generate hello --network testnet
stellar keys secret hello
hello, and show its secret key.
Ensure that you handle secret and private keys securely in production environments and never expose them in your code repositories.
Submitting transaction...
Transaction hash: cef7a63667fe5b0ddcde5562d90e0a40bc04c69616916d1d7fa74a8571bbd82f
Awaiting confirmation...
Transaction successful.
Wasm hash: 275405755441e4be59555bb5c5fd81e84ed21659015d8f3594796c1cf3f380db
stellar contract deploy \
--source-account hello \
--network testnet \
--wasm-hash 275405755441e4be59555bb5c5fd81e84ed21659015d8f3594796c1cf3f380db
# CC6NAQE3ZHRQV3NPQB3F3NYEFBAMEABA4KQTM6A2V5V7PBR5H3UEU3MW