- a key (the identifier for the data),
- a value (the data itself), and
- a Time To Live (TTL), which is how many ledgers remain until the entry is no longer live. (The absolute cutoff is stored on the entry itself as its
liveUntilLedger.)
The extension process
- Build the ledger key for the entry you want to extend.
- Build a transaction containing an
extendFootprintTtloperation with your target TTL, and attach the Soroban transaction data. - Prepare the transaction (this runs simulation to fill in the resources and fee for you), sign it with your secret key, and submit it to the network.
extendFootprintTtl sets a floor, not an exact value. Per the ExtendFootprintTTLOp semantics, the operation guarantees each entry in the read-only footprint lives for at least extendTo ledgers from now. Entries that already live longer than your target are left alone, so a repeated extension is harmless.There’s also a ceiling: an entry can only be extended up to the network’s maximum TTL, which is a network parameter (check the network limits in the Stellar Lab for the current value).Extending a persistent entry
The example below assumes your contract keys its data with a symbol, which is the common case. If your contract uses a vec, a map, or a struct as its storage key, build theScVal that matches instead of reaching for scvSymbol (scval.to_symbol in Python, xdr.ScValTypeScvSymbol in Go, Scv.toSymbol in Java).
The Go SDK has no prepareTransaction, so the Go tab defines a small one. It also defines an extendFootprintTTL helper that builds, prepares, signs, and sends the operation. The later Go tabs reuse both. The Java tab defines the same extendFootprintTTL helper in an ExtendTtl class, and the later Java tabs add methods to that class.
import * as StellarSdk from "@stellar/stellar-sdk";
import { Server } from "@stellar/stellar-sdk/rpc";
async function extendPersistentEntryTTL(
contractId: string,
storageKey: string | Buffer<ArrayBufferLike>,
sourceKeypair: StellarSdk.Keypair,
) {
const server = new Server("https://soroban-testnet.stellar.org");
const account = await server.getAccount(sourceKeypair.publicKey());
// 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));
// Create an identifier for the persistent entry
const persistentEntry = StellarSdk.xdr.LedgerKey.contractData(
new StellarSdk.xdr.LedgerKeyContractData({
contract: StellarSdk.Address.fromString(contractId).toScAddress(),
key: StellarSdk.xdr.ScVal.scvSymbol(storageKey),
durability: StellarSdk.xdr.ContractDataDurability.persistent,
}),
);
// Build the transaction
let transaction: StellarSdk.Transaction | StellarSdk.TransactionBuilder =
new StellarSdk.TransactionBuilder(account, {
fee,
networkPassphrase: StellarSdk.Networks.TESTNET,
})
.addOperation(
StellarSdk.Operation.extendFootprintTtl({
extendTo: 100_000, // The number of ledgers past the LCL (last closed ledger) by which to extend. Roughly 5 days
}),
)
.setTimeout(30);
// Attach Soroban transaction data
const sorobanData = new StellarSdk.SorobanDataBuilder()
.setReadOnly([persistentEntry])
.build();
transaction.setSorobanData(sorobanData);
// Prepare the transaction for signing.
transaction = await server.prepareTransaction(transaction.build());
transaction.sign(sourceKeypair);
return await server.sendTransaction(transaction);
}
from stellar_sdk import (
Address,
Keypair,
Network,
SorobanDataBuilder,
SorobanServer,
TransactionBuilder,
scval,
xdr,
)
from stellar_sdk.soroban_rpc import SendTransactionResponse
def extend_persistent_entry_ttl(
contract_id: str,
storage_key: str,
source_keypair: Keypair,
) -> SendTransactionResponse:
server = SorobanServer("https://soroban-testnet.stellar.org")
account = server.load_account(source_keypair.public_key)
# 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)
# Create an identifier for the persistent entry
persistent_entry = xdr.LedgerKey(
xdr.LedgerEntryType.CONTRACT_DATA,
contract_data=xdr.LedgerKeyContractData(
contract=Address(contract_id).to_xdr_sc_address(),
key=scval.to_symbol(storage_key),
durability=xdr.ContractDataDurability.PERSISTENT,
),
)
# Build the transaction and attach the Soroban transaction data
transaction = (
TransactionBuilder(
source_account=account,
network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
base_fee=fee,
)
.append_extend_footprint_ttl_op(
# The number of ledgers past the LCL (last closed ledger) by which
# to extend. Roughly 5 days
extend_to=100_000,
)
.set_timeout(30)
.set_soroban_data(
SorobanDataBuilder().set_read_only([persistent_entry]).build()
)
.build()
)
# Prepare the transaction for signing.
transaction = server.prepare_transaction(transaction)
transaction.sign(source_keypair)
return server.send_transaction(transaction)
package main
import (
"context"
"fmt"
"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"
)
var server = client.NewClient("https://soroban-testnet.stellar.org", nil)
func extendPersistentEntryTTL(
ctx context.Context,
contractID string,
storageKey string,
sourceKeypair *keypair.Full,
) (protocol.SendTransactionResponse, error) {
// Create an identifier for the persistent entry
contract, err := contractAddress(contractID)
if err != nil {
return protocol.SendTransactionResponse{}, err
}
symbol := xdr.ScSymbol(storageKey)
var persistentEntry xdr.LedgerKey
err = persistentEntry.SetContractData(
contract,
xdr.ScVal{Type: xdr.ScValTypeScvSymbol, Sym: &symbol},
xdr.ContractDataDurabilityPersistent,
)
if err != nil {
return protocol.SendTransactionResponse{}, err
}
// The number of ledgers past the LCL (last closed ledger) by which to extend. Roughly 5 days
return extendFootprintTTL(ctx, sourceKeypair, 100_000, persistentEntry)
}
// extendFootprintTTL builds one ExtendFootprintTtl operation over the given
// read-only keys, then prepares, signs, and sends the transaction.
func extendFootprintTTL(
ctx context.Context,
sourceKeypair *keypair.Full,
extendTo uint32,
keys ...xdr.LedgerKey,
) (protocol.SendTransactionResponse, error) {
var none protocol.SendTransactionResponse
account, err := server.LoadAccount(ctx, sourceKeypair.Address())
if err != nil {
return none, err
}
// 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)
// Build the operation and attach the Soroban transaction data
operation := &txnbuild.ExtendFootprintTtl{
ExtendTo: extendTo,
Ext: xdr.TransactionExt{
V: 1,
SorobanData: &xdr.SorobanTransactionData{
Resources: xdr.SorobanResources{
Footprint: xdr.LedgerFootprint{ReadOnly: keys},
},
},
},
}
// Prepare the transaction for signing.
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
}
return server.SendTransaction(ctx, protocol.SendTransactionRequest{Transaction: envelope})
}
// contractAddress turns a contract ID (C...) into an ScAddress.
func contractAddress(contractID string) (xdr.ScAddress, error) {
decoded, err := strkey.Decode(strkey.VersionByteContract, contractID)
if err != nil {
return xdr.ScAddress{}, err
}
var id xdr.ContractId
copy(id[:], decoded)
return xdr.ScAddress{Type: xdr.ScAddressTypeScAddressTypeContract, ContractId: &id}, nil
}
// prepareTransaction simulates the transaction, then builds it again with the
// simulated footprint, resources, and resource fee.
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
}
// Takes one ExtendFootprintTtl operation; any other type panics here.
operation := params.Operations[0].(*txnbuild.ExtendFootprintTtl)
operation.Ext = xdr.TransactionExt{V: 1, SorobanData: &sorobanData}
// Build again with the same sequence number.
source := tx.SourceAccount()
params.SourceAccount = &source
params.IncrementSequenceNum = false
return txnbuild.NewTransaction(params)
}
import java.util.List;
import org.stellar.sdk.Address;
import org.stellar.sdk.KeyPair;
import org.stellar.sdk.Network;
import org.stellar.sdk.SorobanDataBuilder;
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.ExtendFootprintTTLOperation;
import org.stellar.sdk.responses.sorobanrpc.SendTransactionResponse;
import org.stellar.sdk.scval.Scv;
import org.stellar.sdk.xdr.ContractDataDurability;
import org.stellar.sdk.xdr.LedgerEntryType;
import org.stellar.sdk.xdr.LedgerKey;
public class ExtendTtl {
static final SorobanServer server = new SorobanServer("https://soroban-testnet.stellar.org");
static SendTransactionResponse extendPersistentEntryTTL(
String contractId, String storageKey, KeyPair sourceKeypair) {
// Create an identifier for the persistent entry
LedgerKey persistentEntry = LedgerKey.builder()
.discriminant(LedgerEntryType.CONTRACT_DATA)
.contractData(LedgerKey.LedgerKeyContractData.builder()
.contract(new Address(contractId).toSCAddress())
.key(Scv.toSymbol(storageKey))
.durability(ContractDataDurability.PERSISTENT)
.build())
.build();
// The number of ledgers past the LCL (last closed ledger) by which to extend.
// Roughly 5 days
return extendFootprintTTL(sourceKeypair, 100_000L, persistentEntry);
}
// extendFootprintTTL builds, prepares, signs, and sends an ExtendFootprintTTL
// operation that extends every key in `keys` to the same target.
static SendTransactionResponse extendFootprintTTL(
KeyPair sourceKeypair, long extendTo, LedgerKey... keys) {
TransactionBuilderAccount account = server.getAccount(sourceKeypair.getAccountId());
// 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);
// Build the transaction and attach the Soroban transaction data
Transaction transaction = new TransactionBuilder(account, Network.TESTNET)
.setBaseFee(fee)
.addOperation(ExtendFootprintTTLOperation.builder().extendTo(extendTo).build())
.setTimeout(30)
.setSorobanData(new SorobanDataBuilder().setReadOnly(List.of(keys)).build())
.build();
// Prepare the transaction for signing.
transaction = server.prepareTransaction(transaction);
transaction.sign(sourceKeypair);
return server.sendTransaction(transaction);
}
}
Extending the contract instance
In JavaScript,Contract.getFootprint() hands you the ledger key for the deployed contract instance, so you don’t have to assemble that one by hand. In Python, Go, and Java, build it from the contract address and the SCV_LEDGER_KEY_CONTRACT_INSTANCE value (xdr.ScValTypeScvLedgerKeyContractInstance in Go, Scv.toLedgerKeyContractInstance() in Java).
This extends the contract instance only. The Wasm code the instance points to is a separate ledger entry with its own TTL, and an
extendFootprintTtl operation only touches the keys you actually put in the read-only footprint. A live instance backed by archived code still leaves your contract unusable, so the next section covers the code entry too.If you’re coming from the Rust side, this is a real difference worth internalizing: inside a contract, env.storage().instance().extend_ttl() extends the instance and the code together. The operation used here does not.import * as StellarSdk from "@stellar/stellar-sdk";
import { Server } from "@stellar/stellar-sdk/rpc";
async function extendContractInstanceTTL(
contractId: string,
sourceKeypair: StellarSdk.Keypair,
) {
const server = new Server("https://soroban-testnet.stellar.org");
const account = await server.getAccount(sourceKeypair.publicKey());
// 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));
// Get the ledger key for the contract instance
const contract = new StellarSdk.Contract(contractId);
const footprint = contract.getFootprint();
// Build the transaction
let transaction: StellarSdk.Transaction | StellarSdk.TransactionBuilder =
new StellarSdk.TransactionBuilder(account, {
fee,
networkPassphrase: StellarSdk.Networks.TESTNET,
})
.addOperation(
StellarSdk.Operation.extendFootprintTtl({
extendTo: 100_000, //The number of ledgers past the LCL by which to extend
}),
)
.setTimeout(30);
// Attach Soroban transaction data
const sorobanData = new StellarSdk.SorobanDataBuilder()
.setReadOnly([footprint])
.build();
transaction.setSorobanData(sorobanData);
// Prepare the transaction
transaction = await server.prepareTransaction(transaction.build());
transaction.sign(sourceKeypair);
return await server.sendTransaction(transaction);
}
from stellar_sdk import (
Address,
Keypair,
Network,
SorobanDataBuilder,
SorobanServer,
TransactionBuilder,
xdr,
)
from stellar_sdk.soroban_rpc import SendTransactionResponse
# The ledger key for a deployed contract instance
def contract_instance_key(contract_id: str) -> xdr.LedgerKey:
return xdr.LedgerKey(
xdr.LedgerEntryType.CONTRACT_DATA,
contract_data=xdr.LedgerKeyContractData(
contract=Address(contract_id).to_xdr_sc_address(),
key=xdr.SCVal(xdr.SCValType.SCV_LEDGER_KEY_CONTRACT_INSTANCE),
durability=xdr.ContractDataDurability.PERSISTENT,
),
)
def extend_contract_instance_ttl(
contract_id: str,
source_keypair: Keypair,
) -> SendTransactionResponse:
server = SorobanServer("https://soroban-testnet.stellar.org")
account = server.load_account(source_keypair.public_key)
# 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)
# Get the ledger key for the contract instance
footprint = contract_instance_key(contract_id)
# Build the transaction and attach the Soroban transaction data
transaction = (
TransactionBuilder(
source_account=account,
network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
base_fee=fee,
)
.append_extend_footprint_ttl_op(
extend_to=100_000, # The number of ledgers past the LCL by which to extend
)
.set_timeout(30)
.set_soroban_data(SorobanDataBuilder().set_read_only([footprint]).build())
.build()
)
# Prepare the transaction
transaction = server.prepare_transaction(transaction)
transaction.sign(source_keypair)
return server.send_transaction(transaction)
// contractAddress() and extendFootprintTTL() come from the previous section.
// The ledger key for a deployed contract instance
func contractInstanceKey(contractID string) (xdr.LedgerKey, error) {
var key xdr.LedgerKey
contract, err := contractAddress(contractID)
if err != nil {
return key, err
}
err = key.SetContractData(
contract,
xdr.ScVal{Type: xdr.ScValTypeScvLedgerKeyContractInstance},
xdr.ContractDataDurabilityPersistent,
)
return key, err
}
func extendContractInstanceTTL(
ctx context.Context,
contractID string,
sourceKeypair *keypair.Full,
) (protocol.SendTransactionResponse, error) {
// Get the ledger key for the contract instance
footprint, err := contractInstanceKey(contractID)
if err != nil {
return protocol.SendTransactionResponse{}, err
}
// The number of ledgers past the LCL by which to extend
return extendFootprintTTL(ctx, sourceKeypair, 100_000, footprint)
}
// Add these methods to the ExtendTtl class from the previous section.
// extendFootprintTTL() comes from there too.
// The ledger key for a deployed contract instance
static LedgerKey contractInstanceKey(String contractId) {
return LedgerKey.builder()
.discriminant(LedgerEntryType.CONTRACT_DATA)
.contractData(LedgerKey.LedgerKeyContractData.builder()
.contract(new Address(contractId).toSCAddress())
.key(Scv.toLedgerKeyContractInstance())
.durability(ContractDataDurability.PERSISTENT)
.build())
.build();
}
static SendTransactionResponse extendContractInstanceTTL(
String contractId, KeyPair sourceKeypair) {
// Get the ledger key for the contract instance
LedgerKey footprint = contractInstanceKey(contractId);
// The number of ledgers past the LCL by which to extend
return extendFootprintTTL(sourceKeypair, 100_000L, footprint);
}
Extending the contract code
The code entry is keyed by the Wasm hash rather than by the contract address, and there’s no local way to derive one from the other. That means one extra round trip: read the contract’s instance entry from the network, pull the Wasm hash out of its executable, and build acontractCode ledger key from it.
It’s worth knowing every contract deployed from the same Wasm shares that single code entry, so extending it benefits all of them at once.
import * as StellarSdk from "@stellar/stellar-sdk";
import { Server } from "@stellar/stellar-sdk/rpc";
// Look up the hash of the Wasm code that a deployed contract runs.
async function getWasmHash(server: Server, contractId: string) {
const contract = new StellarSdk.Contract(contractId);
const { entries } = await server.getLedgerEntries(contract.getFootprint());
if (!entries || entries.length === 0) {
throw new Error(`No instance entry found for ${contractId}`);
}
// Each step narrows a union and throws a TypeError if the arm doesn't match
const { contractData } = StellarSdk.xdr.expectUnionVariant(
entries[0].val,
"contractData",
);
const { instance } = StellarSdk.xdr.expectUnionVariant(
contractData.val,
"scvContractInstance",
);
return StellarSdk.xdr.expectUnionVariant(
instance.executable,
"contractExecutableWasm",
).wasmHash;
}
async function extendContractCodeTTL(
contractId: string,
sourceKeypair: StellarSdk.Keypair,
) {
const server = new Server("https://soroban-testnet.stellar.org");
const account = await server.getAccount(sourceKeypair.publicKey());
// 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));
// Create an identifier for the Wasm code entry
const codeEntry = StellarSdk.xdr.LedgerKey.contractCode(
new StellarSdk.xdr.LedgerKeyContractCode({
hash: await getWasmHash(server, contractId),
}),
);
// Build the transaction
let transaction: StellarSdk.Transaction | StellarSdk.TransactionBuilder =
new StellarSdk.TransactionBuilder(account, {
fee,
networkPassphrase: StellarSdk.Networks.TESTNET,
})
.addOperation(
StellarSdk.Operation.extendFootprintTtl({
extendTo: 100_000, // The number of ledgers past the LCL by which to extend
}),
)
.setTimeout(30);
// Attach Soroban transaction data
const sorobanData = new StellarSdk.SorobanDataBuilder()
.setReadOnly([codeEntry])
.build();
transaction.setSorobanData(sorobanData);
// Prepare the transaction
transaction = await server.prepareTransaction(transaction.build());
transaction.sign(sourceKeypair);
return await server.sendTransaction(transaction);
}
from stellar_sdk import (
Keypair,
Network,
SorobanDataBuilder,
SorobanServer,
TransactionBuilder,
xdr,
)
from stellar_sdk.soroban_rpc import SendTransactionResponse
# Look up the hash of the Wasm code that a deployed contract runs.
# contract_instance_key() comes from the previous section.
def get_wasm_hash(server: SorobanServer, contract_id: str) -> xdr.Hash:
entries = server.get_ledger_entries([contract_instance_key(contract_id)]).entries
if not entries:
raise ValueError(f"No instance entry found for {contract_id}")
# Each step checks the union arm and raises a TypeError if it doesn't match
data = xdr.LedgerEntryData.from_xdr(entries[0].xdr)
if data.contract_data is None:
raise TypeError("Expected a contract data entry")
instance = data.contract_data.val.instance
if instance is None:
raise TypeError("Expected a contract instance")
executable = instance.executable
if executable.type != xdr.ContractExecutableType.CONTRACT_EXECUTABLE_WASM:
raise TypeError("Expected a Wasm executable")
return executable.wasm_hash
def extend_contract_code_ttl(
contract_id: str,
source_keypair: Keypair,
) -> SendTransactionResponse:
server = SorobanServer("https://soroban-testnet.stellar.org")
account = server.load_account(source_keypair.public_key)
# 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)
# Create an identifier for the Wasm code entry
code_entry = xdr.LedgerKey(
xdr.LedgerEntryType.CONTRACT_CODE,
contract_code=xdr.LedgerKeyContractCode(
hash=get_wasm_hash(server, contract_id),
),
)
# Build the transaction and attach the Soroban transaction data
transaction = (
TransactionBuilder(
source_account=account,
network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
base_fee=fee,
)
.append_extend_footprint_ttl_op(
extend_to=100_000, # The number of ledgers past the LCL by which to extend
)
.set_timeout(30)
.set_soroban_data(SorobanDataBuilder().set_read_only([code_entry]).build())
.build()
)
# Prepare the transaction
transaction = server.prepare_transaction(transaction)
transaction.sign(source_keypair)
return server.send_transaction(transaction)
// Look up the hash of the Wasm code that a deployed contract runs.
// contractInstanceKey() comes from the previous section.
func getWasmHash(ctx context.Context, contractID string) (xdr.Hash, error) {
key, err := contractInstanceKey(contractID)
if err != nil {
return xdr.Hash{}, err
}
keyXDR, err := xdr.MarshalBase64(key)
if err != nil {
return xdr.Hash{}, err
}
response, err := server.GetLedgerEntries(ctx, protocol.GetLedgerEntriesRequest{
Keys: []string{keyXDR},
})
if err != nil {
return xdr.Hash{}, err
}
if len(response.Entries) == 0 {
return xdr.Hash{}, fmt.Errorf("no instance entry found for %s", contractID)
}
// Each step checks the union arm and returns an error if it doesn't match
var data xdr.LedgerEntryData
if err := xdr.SafeUnmarshalBase64(response.Entries[0].DataXDR, &data); err != nil {
return xdr.Hash{}, err
}
contractData, ok := data.GetContractData()
if !ok {
return xdr.Hash{}, fmt.Errorf("expected a contract data entry")
}
instance, ok := contractData.Val.GetInstance()
if !ok {
return xdr.Hash{}, fmt.Errorf("expected a contract instance")
}
wasmHash, ok := instance.Executable.GetWasmHash()
if !ok {
return xdr.Hash{}, fmt.Errorf("expected a Wasm executable")
}
return wasmHash, nil
}
func extendContractCodeTTL(
ctx context.Context,
contractID string,
sourceKeypair *keypair.Full,
) (protocol.SendTransactionResponse, error) {
// Create an identifier for the Wasm code entry
wasmHash, err := getWasmHash(ctx, contractID)
if err != nil {
return protocol.SendTransactionResponse{}, err
}
var codeEntry xdr.LedgerKey
if err := codeEntry.SetContractCode(wasmHash); err != nil {
return protocol.SendTransactionResponse{}, err
}
// The number of ledgers past the LCL by which to extend
return extendFootprintTTL(ctx, sourceKeypair, 100_000, codeEntry)
}
// Add these imports to the ExtendTtl class:
//
// import org.stellar.sdk.responses.sorobanrpc.GetLedgerEntriesResponse;
// import org.stellar.sdk.xdr.ContractExecutable;
// import org.stellar.sdk.xdr.ContractExecutableType;
// import org.stellar.sdk.xdr.Hash;
// import org.stellar.sdk.xdr.LedgerEntry;
// import org.stellar.sdk.xdr.SCVal;
// Look up the hash of the Wasm code that a deployed contract runs.
// contractInstanceKey() comes from the previous section.
static Hash getWasmHash(String contractId) {
GetLedgerEntriesResponse response =
server.getLedgerEntries(List.of(contractInstanceKey(contractId)));
if (response.getEntries() == null || response.getEntries().isEmpty()) {
throw new IllegalStateException("No instance entry found for " + contractId);
}
// Each step checks the union arm and throws if it doesn't match
LedgerEntry.LedgerEntryData data = response.getEntries().get(0).parseXdr();
if (data.getDiscriminant() != LedgerEntryType.CONTRACT_DATA) {
throw new IllegalArgumentException("Expected a contract data entry");
}
SCVal val = data.getContractData().getVal();
if (val.getInstance() == null) {
throw new IllegalArgumentException("Expected a contract instance");
}
ContractExecutable executable = val.getInstance().getExecutable();
if (executable.getDiscriminant() != ContractExecutableType.CONTRACT_EXECUTABLE_WASM) {
throw new IllegalArgumentException("Expected a Wasm executable");
}
return executable.getWasm_hash();
}
static SendTransactionResponse extendContractCodeTTL(String contractId, KeyPair sourceKeypair) {
// Create an identifier for the Wasm code entry
LedgerKey codeEntry = LedgerKey.builder()
.discriminant(LedgerEntryType.CONTRACT_CODE)
.contractCode(LedgerKey.LedgerKeyContractCode.builder().hash(getWasmHash(contractId)).build())
.build();
// The number of ledgers past the LCL by which to extend
return extendFootprintTTL(sourceKeypair, 100_000L, codeEntry);
}
getWasmHash assumes the contract runs an executable that was deployed. A Stellar Asset Contract instance has a built-in executable instead of a Wasm hash, so getWasmHash throws a TypeError for one of those (in Go, it returns an error; in Java, it throws an IllegalArgumentException). Check instance.executable.type first if your code has to handle both.Extending all three together
A Soroban operation has to be the only operation in its transaction, so you might expect to need one transaction per entry. Happily, you don’t. A singleExtendFootprintTTLOp extends every entry listed in the transaction’s read-only footprint, applying the same extendTo target to all of them. When a batch of entries should live until the same ledger, list them all in one footprint and extend them together. Here’s all three at once, reusing the getWasmHash helper (get_wasm_hash in Python) from the previous section:
import * as StellarSdk from "@stellar/stellar-sdk";
import { Server } from "@stellar/stellar-sdk/rpc";
async function extendContractAndPersistentEntry(
contractId: string,
storageKey: string | Buffer<ArrayBufferLike>,
sourceKeypair: StellarSdk.Keypair,
) {
const server = new Server("https://soroban-testnet.stellar.org");
const account = await server.getAccount(sourceKeypair.publicKey());
// 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));
// Ledger key for the persistent entry...
const persistentEntry = StellarSdk.xdr.LedgerKey.contractData(
new StellarSdk.xdr.LedgerKeyContractData({
contract: StellarSdk.Address.fromString(contractId).toScAddress(),
key: StellarSdk.xdr.ScVal.scvSymbol(storageKey),
durability: StellarSdk.xdr.ContractDataDurability.persistent,
}),
);
// ...the contract instance...
const contract = new StellarSdk.Contract(contractId);
// ...and the Wasm code that instance runs.
const codeEntry = StellarSdk.xdr.LedgerKey.contractCode(
new StellarSdk.xdr.LedgerKeyContractCode({
hash: await getWasmHash(server, contractId),
}),
);
// A single ExtendFootprintTtl operation extends the whole read-only footprint.
let transaction: StellarSdk.Transaction | StellarSdk.TransactionBuilder =
new StellarSdk.TransactionBuilder(account, {
fee,
networkPassphrase: StellarSdk.Networks.TESTNET,
})
.addOperation(
StellarSdk.Operation.extendFootprintTtl({
extendTo: 100_000, // one shared target, applied to every key below
}),
)
.setTimeout(30);
// List every key to extend together in one read-only footprint.
const sorobanData = new StellarSdk.SorobanDataBuilder()
.setReadOnly([persistentEntry, contract.getFootprint(), codeEntry])
.build();
transaction.setSorobanData(sorobanData);
transaction = await server.prepareTransaction(transaction.build());
transaction.sign(sourceKeypair);
return await server.sendTransaction(transaction);
}
from stellar_sdk import (
Address,
Keypair,
Network,
SorobanDataBuilder,
SorobanServer,
TransactionBuilder,
scval,
xdr,
)
from stellar_sdk.soroban_rpc import SendTransactionResponse
# contract_instance_key() and get_wasm_hash() come from the previous sections.
def extend_contract_and_persistent_entry(
contract_id: str,
storage_key: str,
source_keypair: Keypair,
) -> SendTransactionResponse:
server = SorobanServer("https://soroban-testnet.stellar.org")
account = server.load_account(source_keypair.public_key)
# 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)
# Ledger key for the persistent entry...
persistent_entry = xdr.LedgerKey(
xdr.LedgerEntryType.CONTRACT_DATA,
contract_data=xdr.LedgerKeyContractData(
contract=Address(contract_id).to_xdr_sc_address(),
key=scval.to_symbol(storage_key),
durability=xdr.ContractDataDurability.PERSISTENT,
),
)
# ...the contract instance...
instance_entry = contract_instance_key(contract_id)
# ...and the Wasm code that instance runs.
code_entry = xdr.LedgerKey(
xdr.LedgerEntryType.CONTRACT_CODE,
contract_code=xdr.LedgerKeyContractCode(
hash=get_wasm_hash(server, contract_id),
),
)
# A single ExtendFootprintTTL operation extends the whole read-only footprint.
transaction = (
TransactionBuilder(
source_account=account,
network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
base_fee=fee,
)
.append_extend_footprint_ttl_op(
extend_to=100_000, # one shared target, applied to every key below
)
.set_timeout(30)
# List every key to extend together in one read-only footprint.
.set_soroban_data(
SorobanDataBuilder()
.set_read_only([persistent_entry, instance_entry, code_entry])
.build()
)
.build()
)
transaction = server.prepare_transaction(transaction)
transaction.sign(source_keypair)
return server.send_transaction(transaction)
// contractAddress(), contractInstanceKey(), getWasmHash(), and
// extendFootprintTTL() come from the previous sections.
func extendContractAndPersistentEntry(
ctx context.Context,
contractID string,
storageKey string,
sourceKeypair *keypair.Full,
) (protocol.SendTransactionResponse, error) {
var none protocol.SendTransactionResponse
// Ledger key for the persistent entry...
contract, err := contractAddress(contractID)
if err != nil {
return none, err
}
symbol := xdr.ScSymbol(storageKey)
var persistentEntry xdr.LedgerKey
err = persistentEntry.SetContractData(
contract,
xdr.ScVal{Type: xdr.ScValTypeScvSymbol, Sym: &symbol},
xdr.ContractDataDurabilityPersistent,
)
if err != nil {
return none, err
}
// ...the contract instance...
instanceEntry, err := contractInstanceKey(contractID)
if err != nil {
return none, err
}
// ...and the Wasm code that instance runs.
wasmHash, err := getWasmHash(ctx, contractID)
if err != nil {
return none, err
}
var codeEntry xdr.LedgerKey
if err := codeEntry.SetContractCode(wasmHash); err != nil {
return none, err
}
// A single ExtendFootprintTtl operation extends the whole read-only footprint,
// with one shared target applied to every key.
return extendFootprintTTL(ctx, sourceKeypair, 100_000, persistentEntry, instanceEntry, codeEntry)
}
// contractInstanceKey(), getWasmHash(), and extendFootprintTTL() come from
// the previous sections.
static SendTransactionResponse extendContractAndPersistentEntry(
String contractId, String storageKey, KeyPair sourceKeypair) {
// Ledger key for the persistent entry...
LedgerKey persistentEntry = LedgerKey.builder()
.discriminant(LedgerEntryType.CONTRACT_DATA)
.contractData(LedgerKey.LedgerKeyContractData.builder()
.contract(new Address(contractId).toSCAddress())
.key(Scv.toSymbol(storageKey))
.durability(ContractDataDurability.PERSISTENT)
.build())
.build();
// ...the contract instance...
LedgerKey instanceEntry = contractInstanceKey(contractId);
// ...and the Wasm code that instance runs.
LedgerKey codeEntry = LedgerKey.builder()
.discriminant(LedgerEntryType.CONTRACT_CODE)
.contractCode(LedgerKey.LedgerKeyContractCode.builder().hash(getWasmHash(contractId)).build())
.build();
// A single ExtendFootprintTTL operation extends the whole read-only footprint,
// with one shared target applied to every key.
return extendFootprintTTL(sourceKeypair, 100_000L, persistentEntry, instanceEntry, codeEntry);
}
extendTo is the one real constraint. Entries that need different target TTLs can’t share an operation, so extend each one in its own transaction. That’s exactly what the extendPersistentEntryTTL, extendContractInstanceTTL, and extendContractCodeTTL helpers above do: each builds its own operation, so each can carry its own extendTo target.
Batching keys into one footprint grows the transaction’s resource usage, since
diskReadBytes has to cover the serialized size of every entry in the read-only set. server.prepareTransaction works that out for you, but a large enough batch can bump into the network’s transaction limits. If that happens, split the batch across a few transactions.const contractId = "CBEE2DHGMYRKJKSJO5E55LBKFMPXE57ZWKTXTCRMC5ANIRJ7IW2Y2WVE";
const storageKey = "BALANCE";
const sourceKeypair = StellarSdk.Keypair.fromSecret(
"SXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
);
extendPersistentEntryTTL(contractId, storageKey, sourceKeypair)
.then((result) => console.log("Extension successful:", result))
.catch((error) => console.error("Extension failed:", error));
contract_id = "CBEE2DHGMYRKJKSJO5E55LBKFMPXE57ZWKTXTCRMC5ANIRJ7IW2Y2WVE"
storage_key = "BALANCE"
source_keypair = Keypair.from_secret("SXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
try:
result = extend_persistent_entry_ttl(contract_id, storage_key, source_keypair)
print("Extension successful:", result)
except Exception as error:
print("Extension failed:", error)
func main() {
contractID := "CBEE2DHGMYRKJKSJO5E55LBKFMPXE57ZWKTXTCRMC5ANIRJ7IW2Y2WVE"
storageKey := "BALANCE"
sourceKeypair := keypair.MustParseFull("SXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
result, err := extendPersistentEntryTTL(context.Background(), contractID, storageKey, sourceKeypair)
if err != nil {
fmt.Println("Extension failed:", err)
return
}
fmt.Println("Extension successful:", result)
}
public static void main(String[] args) {
String contractId = "CBEE2DHGMYRKJKSJO5E55LBKFMPXE57ZWKTXTCRMC5ANIRJ7IW2Y2WVE";
String storageKey = "BALANCE";
KeyPair sourceKeypair = KeyPair.fromSecretSeed("SXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
try {
SendTransactionResponse result =
extendPersistentEntryTTL(contractId, storageKey, sourceKeypair);
System.out.println("Extension successful: " + result);
} catch (Exception error) {
System.err.println("Extension failed: " + error);
}
}