Prerequisites
Before you begin, ensure you have the following installed:- Rust and Cargo (for compiling smart contracts)
- Node.js and npm (for running JavaScript deployment scripts), Python 3.10 or later (for running Python deployment scripts), Go 1.25 or later (for running Go deployment scripts), or Java 17 or later and Maven (for running Java deployment scripts)
- Stellar CLI
Initialize a sample Rust Contract
stellar contract init hello-world
cd hello-world
stellar contract build
hello-world/target/wasm32v1-none/release/hello_world.wasm
Create a Node Project
- Create a new directory for your Node.js project and navigate into it:
mkdir deploy-contract
cd deploy-contract
- Initialize a new Node.js project and install necessary dependencies:
npm init -y
npm install @stellar/stellar-sdk
pip install stellar-sdk
go mod init deploy-contract
go get github.com/stellar/go-stellar-sdk
<dependencies> section of its pom.xml:
<dependency>
<groupId>network.lightsail</groupId>
<artifactId>stellar-sdk</artifactId>
<version>6.0.0</version>
</dependency>
Set Up Deployment Scripts
Imports
Import necessary modules in your script. In JavaScript, save the file asdeploy.mjs to enable ES module imports. In Go, save it as main.go. In Java, save it as src/main/java/DeployContract.java:
import * as StellarSDK from "@stellar/stellar-sdk";
import fs from "fs";
from stellar_sdk import Keypair, Network, SorobanServer, TransactionBuilder, scval
from stellar_sdk.soroban_rpc import GetTransactionStatus, SendTransactionStatus
from stellar_sdk.xdr import TransactionMeta
package main
import (
"context"
"crypto/rand"
"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/strkey"
"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"
)
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.stellar.sdk.Address;
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;
import org.stellar.sdk.scval.Scv;
import org.stellar.sdk.xdr.SCVal;
import org.stellar.sdk.xdr.TransactionMeta;
Installing the Wasm on the network
Create a function to upload the compiled Wasm file:async function uploadWasm(filePath) {
const bytecode = fs.readFileSync(filePath);
const account = await server.getAccount(sourceKeypair.publicKey());
const operation = StellarSDK.Operation.uploadContractWasm({ wasm: bytecode });
return await buildAndSendTransaction(account, operation);
}
def upload_wasm(file_path):
with open(file_path, "rb") as f:
bytecode = f.read()
account = server.load_account(source_keypair.public_key)
return build_and_send_transaction(
account, lambda builder: builder.append_upload_contract_wasm_op(bytecode)
)
func uploadWasm(ctx context.Context, filePath string) (protocol.GetTransactionResponse, error) {
bytecode, err := os.ReadFile(filePath)
if err != nil {
return protocol.GetTransactionResponse{}, err
}
account, err := server.LoadAccount(ctx, sourceKeypair.Address())
if err != nil {
return protocol.GetTransactionResponse{}, err
}
operation := &txnbuild.InvokeHostFunction{
HostFunction: xdr.HostFunction{
Type: xdr.HostFunctionTypeHostFunctionTypeUploadContractWasm,
Wasm: &bytecode,
},
SourceAccount: sourceKeypair.Address(),
}
return buildAndSendTransaction(ctx, account, operation)
}
static GetTransactionResponse uploadWasm(String filePath) throws Exception {
byte[] bytecode = Files.readAllBytes(Path.of(filePath));
TransactionBuilderAccount account = server.getAccount(sourceKeypair.getAccountId());
InvokeHostFunctionOperation operation =
InvokeHostFunctionOperation.uploadContractWasmOperationBuilder(bytecode).build();
return buildAndSendTransaction(account, operation);
}
uploadContractWasm Stellar operation, which when wrapped in a transaction is sent to the network.
Deploy contract
Deploy the contract by referencing the Wasm hash:async function deployContract(response) {
const account = await server.getAccount(sourceKeypair.publicKey());
const operation = StellarSDK.Operation.createCustomContract({
wasmHash: StellarSDK.scValToNative(response.returnValue),
address: StellarSDK.Address.fromString(sourceKeypair.publicKey()),
});
const responseDeploy = await buildAndSendTransaction(account, operation);
const contractAddress = StellarSDK.scValToNative(responseDeploy.returnValue);
console.log(contractAddress);
}
def deploy_contract(response):
account = server.load_account(source_keypair.public_key)
wasm_hash = scval.to_native(get_return_value(response))
response_deploy = build_and_send_transaction(
account,
lambda builder: builder.append_create_contract_op(
wasm_id=wasm_hash, address=source_keypair.public_key
),
)
contract_address = scval.to_native(get_return_value(response_deploy))
print(contract_address.address)
func deployContract(ctx context.Context, response protocol.GetTransactionResponse) error {
account, err := server.LoadAccount(ctx, sourceKeypair.Address())
if err != nil {
return err
}
returnValue, err := getReturnValue(response)
if err != nil {
return err
}
wasmHashBytes, ok := returnValue.GetBytes()
if !ok || len(wasmHashBytes) != 32 {
return errors.New("upload did not return a Wasm hash")
}
var wasmHash xdr.Hash
copy(wasmHash[:], wasmHashBytes)
// A random salt, as createCustomContract uses in JavaScript
var salt xdr.Uint256
if _, err := rand.Read(salt[:]); err != nil {
return err
}
operation := &txnbuild.InvokeHostFunction{
HostFunction: xdr.HostFunction{
Type: xdr.HostFunctionTypeHostFunctionTypeCreateContractV2,
CreateContractV2: &xdr.CreateContractArgsV2{
ContractIdPreimage: xdr.ContractIdPreimage{
Type: xdr.ContractIdPreimageTypeContractIdPreimageFromAddress,
FromAddress: &xdr.ContractIdPreimageFromAddress{
Address: xdr.ScAddress{
Type: xdr.ScAddressTypeScAddressTypeAccount,
AccountId: xdr.MustAddressPtr(sourceKeypair.Address()),
},
Salt: salt,
},
},
Executable: xdr.ContractExecutable{
Type: xdr.ContractExecutableTypeContractExecutableWasm,
WasmHash: &wasmHash,
},
ConstructorArgs: []xdr.ScVal{},
},
},
SourceAccount: sourceKeypair.Address(),
}
responseDeploy, err := buildAndSendTransaction(ctx, account, operation)
if err != nil {
return err
}
contractValue, err := getReturnValue(responseDeploy)
if err != nil {
return err
}
contractAddress, ok := contractValue.GetAddress()
if !ok || contractAddress.ContractId == nil {
return errors.New("deploy did not return a contract address")
}
fmt.Println(strkey.MustEncode(strkey.VersionByteContract, (*contractAddress.ContractId)[:]))
return nil
}
static void deployContract(GetTransactionResponse response) throws Exception {
TransactionBuilderAccount account = server.getAccount(sourceKeypair.getAccountId());
byte[] wasmHash = Scv.fromBytes(getReturnValue(response));
// A null salt makes the SDK pick a random one, as createCustomContract does in JavaScript
InvokeHostFunctionOperation operation = InvokeHostFunctionOperation.createContractOperationBuilder(
wasmHash, new Address(sourceKeypair.getAccountId()), List.of(), null)
.build();
GetTransactionResponse responseDeploy = buildAndSendTransaction(account, operation);
Address contractAddress = Address.fromSCVal(getReturnValue(responseDeploy));
System.out.println(contractAddress);
}
createCustomContract stellar operation, which when wrapped in a transaction is sent to the network, generating a contract address. scValToNative converts each return value to a JavaScript value: the Wasm hash bytes after the upload, and the contract address string after the deploy. In Python, append_create_contract_op adds the same operation, and scval.to_native converts the return values: the Wasm hash to bytes, and the contract address to an Address. In Go, the code builds the same CreateContractV2 host function by hand, reads the Wasm hash with GetBytes, and encodes the contract ID as a C... address with strkey. In Java, createContractOperationBuilder builds the same operation, Scv.fromBytes reads the Wasm hash, and Address.fromSCVal turns the return value into a C... address.
Building, Signing and Sending the Transaction
Handle the building, signing, and sending of transactions: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}`);
}
}
def build_and_send_transaction(account, add_operation):
# Bid what recent transactions paid, capped at what you're willing to spend.
# 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)
builder = TransactionBuilder(
source_account=account,
network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
base_fee=fee,
)
add_operation(builder)
transaction = builder.set_timeout(30).build()
tx = server.prepare_transaction(transaction)
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 RuntimeError(f"Transaction not accepted: {send_response.status}")
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 RuntimeError("Not confirmed yet. Check again before resending.")
if response.status == GetTransactionStatus.SUCCESS:
print("Transaction successful.")
return response
print("Transaction failed.")
raise RuntimeError(f"Transaction did not succeed: {response.status}")
def get_return_value(response):
# The contract's return value is in the transaction meta.
meta = TransactionMeta.from_xdr(response.result_meta_xdr)
meta_body = meta.v4 or meta.v3
return meta_body.soroban_meta.return_value
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)
}
func getReturnValue(response protocol.GetTransactionResponse) (xdr.ScVal, error) {
// The contract's return value is in the transaction meta.
var meta xdr.TransactionMeta
if err := xdr.SafeUnmarshalBase64(response.ResultMetaXDR, &meta); err != nil {
return xdr.ScVal{}, err
}
switch {
case meta.V4 != nil && meta.V4.SorobanMeta != nil && meta.V4.SorobanMeta.ReturnValue != nil:
return *meta.V4.SorobanMeta.ReturnValue, nil
case meta.V3 != nil && meta.V3.SorobanMeta != nil:
return meta.V3.SorobanMeta.ReturnValue, nil
}
return xdr.ScVal{}, errors.New("no return value in the transaction meta")
}
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());
}
static SCVal getReturnValue(GetTransactionResponse response) {
// The contract's return value is in the transaction meta.
TransactionMeta meta = response.parseResultMetaXdr();
if (meta.getV4() != null && meta.getV4().getSorobanMeta() != null
&& meta.getV4().getSorobanMeta().getReturnValue() != null) {
return meta.getV4().getSorobanMeta().getReturnValue();
}
if (meta.getV3() != null && meta.getV3().getSorobanMeta() != null) {
return meta.getV3().getSorobanMeta().getReturnValue();
}
throw new IllegalStateException("no return value in the transaction meta");
}
sendTransaction status first: TRY_AGAIN_LATER and ERROR mean the network did not accept the transaction, so the function stops with an error. Then server.pollTransaction waits for the result and stops after 30 attempts, so the script never hangs. If the attempts run out, the status is still NOT_FOUND. That means the result is unknown, not that the transaction failed, so check again before you resend it. Submit a transaction and wait shows the full handling. For the SDK’s own flow, read its Invoke a Contract guide.
The Python version also defines get_return_value. The Python SDK’s response has no return value field, so the helper reads it from the transaction meta in result_meta_xdr. The Go version does the same with getReturnValue and ResultMetaXDR. The Go SDK has no prepareTransaction, so the Go version defines one: it simulates the transaction, then adds the simulated resources, resource fee, and authorization entries. The Java SDK has prepareTransaction, but its response has no return value field either, so the Java version reads it from the transaction meta with getReturnValue.
Running the Script
Execute the deployment script:const server = new StellarSDK.rpc.Server(
"https://soroban-testnet.stellar.org:443",
);
const sourceKeypair = StellarSDK.Keypair.fromSecret("Your_Secret_Key");
const wasmFilePath =
"../hello-world/target/wasm32v1-none/release/hello_world.wasm"; // Adjust this path as necessary
try {
let uploadResponse = await uploadWasm(wasmFilePath);
await deployContract(uploadResponse);
} catch (error) {
console.error(error);
}
server = SorobanServer("https://soroban-testnet.stellar.org:443")
source_keypair = Keypair.from_secret("Your_Secret_Key")
# Adjust this path as necessary
wasm_file_path = "../hello-world/target/wasm32v1-none/release/hello_world.wasm"
try:
upload_response = upload_wasm(wasm_file_path)
deploy_contract(upload_response)
except Exception as error:
print(error)
var server = client.NewClient("https://soroban-testnet.stellar.org:443", nil)
var sourceKeypair = keypair.MustParseFull("Your_Secret_Key")
// Adjust this path as necessary
const wasmFilePath = "../hello-world/target/wasm32v1-none/release/hello_world.wasm"
func main() {
ctx := context.Background()
uploadResponse, err := uploadWasm(ctx, wasmFilePath)
if err != nil {
log.Fatal(err)
}
if err := deployContract(ctx, uploadResponse); err != nil {
log.Fatal(err)
}
}
static final SorobanServer server = new SorobanServer("https://soroban-testnet.stellar.org:443");
static final KeyPair sourceKeypair = KeyPair.fromSecretSeed("Your_Secret_Key");
// Adjust this path as necessary
static final String wasmFilePath = "../hello-world/target/wasm32v1-none/release/hello_world.wasm";
public static void main(String[] args) {
try {
GetTransactionResponse uploadResponse = uploadWasm(wasmFilePath);
deployContract(uploadResponse);
} catch (Exception error) {
System.err.println(error);
}
}
go run main.go. In Java, the fields, methods, and main above go in one class, as the complete script below shows.
This is just demo code, so ensure that you handle secrets and private keys securely in production environments and never expose them in your code repositories. This guide should provide you with a clear path to installing and deploying your smart contracts using JavaScript, Python, Go, or Java code.
Complete Script
Here are all the snippets stacked together in a single file for convenience:import * as StellarSDK from "@stellar/stellar-sdk";
import fs from "fs";
async function uploadWasm(filePath) {
const bytecode = fs.readFileSync(filePath);
const account = await server.getAccount(sourceKeypair.publicKey());
const operation = StellarSDK.Operation.uploadContractWasm({ wasm: bytecode });
return await buildAndSendTransaction(account, operation);
}
async function deployContract(response) {
const account = await server.getAccount(sourceKeypair.publicKey());
const operation = StellarSDK.Operation.createCustomContract({
wasmHash: StellarSDK.scValToNative(response.returnValue),
address: StellarSDK.Address.fromString(sourceKeypair.publicKey()),
});
const responseDeploy = await buildAndSendTransaction(account, operation);
const contractAddress = StellarSDK.scValToNative(responseDeploy.returnValue);
console.log(contractAddress);
}
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}`);
}
}
const server = new StellarSDK.rpc.Server(
"https://soroban-testnet.stellar.org:443",
);
const sourceKeypair = StellarSDK.Keypair.fromSecret("Your_Secret_Key");
const wasmFilePath =
"../hello-world/target/wasm32v1-none/release/hello_world.wasm"; // Adjust this path as necessary
try {
let uploadResponse = await uploadWasm(wasmFilePath);
await deployContract(uploadResponse);
} catch (error) {
console.error(error);
}
from stellar_sdk import Keypair, Network, SorobanServer, TransactionBuilder, scval
from stellar_sdk.soroban_rpc import GetTransactionStatus, SendTransactionStatus
from stellar_sdk.xdr import TransactionMeta
def upload_wasm(file_path):
with open(file_path, "rb") as f:
bytecode = f.read()
account = server.load_account(source_keypair.public_key)
return build_and_send_transaction(
account, lambda builder: builder.append_upload_contract_wasm_op(bytecode)
)
def deploy_contract(response):
account = server.load_account(source_keypair.public_key)
wasm_hash = scval.to_native(get_return_value(response))
response_deploy = build_and_send_transaction(
account,
lambda builder: builder.append_create_contract_op(
wasm_id=wasm_hash, address=source_keypair.public_key
),
)
contract_address = scval.to_native(get_return_value(response_deploy))
print(contract_address.address)
def build_and_send_transaction(account, add_operation):
# Bid what recent transactions paid, capped at what you're willing to spend.
# 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)
builder = TransactionBuilder(
source_account=account,
network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
base_fee=fee,
)
add_operation(builder)
transaction = builder.set_timeout(30).build()
tx = server.prepare_transaction(transaction)
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 RuntimeError(f"Transaction not accepted: {send_response.status}")
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 RuntimeError("Not confirmed yet. Check again before resending.")
if response.status == GetTransactionStatus.SUCCESS:
print("Transaction successful.")
return response
print("Transaction failed.")
raise RuntimeError(f"Transaction did not succeed: {response.status}")
def get_return_value(response):
# The contract's return value is in the transaction meta.
meta = TransactionMeta.from_xdr(response.result_meta_xdr)
meta_body = meta.v4 or meta.v3
return meta_body.soroban_meta.return_value
server = SorobanServer("https://soroban-testnet.stellar.org:443")
source_keypair = Keypair.from_secret("Your_Secret_Key")
# Adjust this path as necessary
wasm_file_path = "../hello-world/target/wasm32v1-none/release/hello_world.wasm"
try:
upload_response = upload_wasm(wasm_file_path)
deploy_contract(upload_response)
except Exception as error:
print(error)
package main
import (
"context"
"crypto/rand"
"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/strkey"
"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"
)
func uploadWasm(ctx context.Context, filePath string) (protocol.GetTransactionResponse, error) {
bytecode, err := os.ReadFile(filePath)
if err != nil {
return protocol.GetTransactionResponse{}, err
}
account, err := server.LoadAccount(ctx, sourceKeypair.Address())
if err != nil {
return protocol.GetTransactionResponse{}, err
}
operation := &txnbuild.InvokeHostFunction{
HostFunction: xdr.HostFunction{
Type: xdr.HostFunctionTypeHostFunctionTypeUploadContractWasm,
Wasm: &bytecode,
},
SourceAccount: sourceKeypair.Address(),
}
return buildAndSendTransaction(ctx, account, operation)
}
func deployContract(ctx context.Context, response protocol.GetTransactionResponse) error {
account, err := server.LoadAccount(ctx, sourceKeypair.Address())
if err != nil {
return err
}
returnValue, err := getReturnValue(response)
if err != nil {
return err
}
wasmHashBytes, ok := returnValue.GetBytes()
if !ok || len(wasmHashBytes) != 32 {
return errors.New("upload did not return a Wasm hash")
}
var wasmHash xdr.Hash
copy(wasmHash[:], wasmHashBytes)
// A random salt, as createCustomContract uses in JavaScript
var salt xdr.Uint256
if _, err := rand.Read(salt[:]); err != nil {
return err
}
operation := &txnbuild.InvokeHostFunction{
HostFunction: xdr.HostFunction{
Type: xdr.HostFunctionTypeHostFunctionTypeCreateContractV2,
CreateContractV2: &xdr.CreateContractArgsV2{
ContractIdPreimage: xdr.ContractIdPreimage{
Type: xdr.ContractIdPreimageTypeContractIdPreimageFromAddress,
FromAddress: &xdr.ContractIdPreimageFromAddress{
Address: xdr.ScAddress{
Type: xdr.ScAddressTypeScAddressTypeAccount,
AccountId: xdr.MustAddressPtr(sourceKeypair.Address()),
},
Salt: salt,
},
},
Executable: xdr.ContractExecutable{
Type: xdr.ContractExecutableTypeContractExecutableWasm,
WasmHash: &wasmHash,
},
ConstructorArgs: []xdr.ScVal{},
},
},
SourceAccount: sourceKeypair.Address(),
}
responseDeploy, err := buildAndSendTransaction(ctx, account, operation)
if err != nil {
return err
}
contractValue, err := getReturnValue(responseDeploy)
if err != nil {
return err
}
contractAddress, ok := contractValue.GetAddress()
if !ok || contractAddress.ContractId == nil {
return errors.New("deploy did not return a contract address")
}
fmt.Println(strkey.MustEncode(strkey.VersionByteContract, (*contractAddress.ContractId)[:]))
return nil
}
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)
}
func getReturnValue(response protocol.GetTransactionResponse) (xdr.ScVal, error) {
// The contract's return value is in the transaction meta.
var meta xdr.TransactionMeta
if err := xdr.SafeUnmarshalBase64(response.ResultMetaXDR, &meta); err != nil {
return xdr.ScVal{}, err
}
switch {
case meta.V4 != nil && meta.V4.SorobanMeta != nil && meta.V4.SorobanMeta.ReturnValue != nil:
return *meta.V4.SorobanMeta.ReturnValue, nil
case meta.V3 != nil && meta.V3.SorobanMeta != nil:
return meta.V3.SorobanMeta.ReturnValue, nil
}
return xdr.ScVal{}, errors.New("no return value in the transaction meta")
}
var server = client.NewClient("https://soroban-testnet.stellar.org:443", nil)
var sourceKeypair = keypair.MustParseFull("Your_Secret_Key")
// Adjust this path as necessary
const wasmFilePath = "../hello-world/target/wasm32v1-none/release/hello_world.wasm"
func main() {
ctx := context.Background()
uploadResponse, err := uploadWasm(ctx, wasmFilePath)
if err != nil {
log.Fatal(err)
}
if err := deployContract(ctx, uploadResponse); err != nil {
log.Fatal(err)
}
}
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.stellar.sdk.Address;
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;
import org.stellar.sdk.scval.Scv;
import org.stellar.sdk.xdr.SCVal;
import org.stellar.sdk.xdr.TransactionMeta;
public final class DeployContract {
static final SorobanServer server = new SorobanServer("https://soroban-testnet.stellar.org:443");
static final KeyPair sourceKeypair = KeyPair.fromSecretSeed("Your_Secret_Key");
// Adjust this path as necessary
static final String wasmFilePath = "../hello-world/target/wasm32v1-none/release/hello_world.wasm";
static GetTransactionResponse uploadWasm(String filePath) throws Exception {
byte[] bytecode = Files.readAllBytes(Path.of(filePath));
TransactionBuilderAccount account = server.getAccount(sourceKeypair.getAccountId());
InvokeHostFunctionOperation operation =
InvokeHostFunctionOperation.uploadContractWasmOperationBuilder(bytecode).build();
return buildAndSendTransaction(account, operation);
}
static void deployContract(GetTransactionResponse response) throws Exception {
TransactionBuilderAccount account = server.getAccount(sourceKeypair.getAccountId());
byte[] wasmHash = Scv.fromBytes(getReturnValue(response));
// A null salt makes the SDK pick a random one, as createCustomContract does in JavaScript
InvokeHostFunctionOperation operation = InvokeHostFunctionOperation.createContractOperationBuilder(
wasmHash, new Address(sourceKeypair.getAccountId()), List.of(), null)
.build();
GetTransactionResponse responseDeploy = buildAndSendTransaction(account, operation);
Address contractAddress = Address.fromSCVal(getReturnValue(responseDeploy));
System.out.println(contractAddress);
}
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());
}
static SCVal getReturnValue(GetTransactionResponse response) {
// The contract's return value is in the transaction meta.
TransactionMeta meta = response.parseResultMetaXdr();
if (meta.getV4() != null && meta.getV4().getSorobanMeta() != null
&& meta.getV4().getSorobanMeta().getReturnValue() != null) {
return meta.getV4().getSorobanMeta().getReturnValue();
}
if (meta.getV3() != null && meta.getV3().getSorobanMeta() != null) {
return meta.getV3().getSorobanMeta().getReturnValue();
}
throw new IllegalStateException("no return value in the transaction meta");
}
public static void main(String[] args) {
try {
GetTransactionResponse uploadResponse = uploadWasm(wasmFilePath);
deployContract(uploadResponse);
} catch (Exception error) {
System.err.println(error);
}
}
}