Members
# constant AuthClawbackEnabledFlag
When set using Operation.setOptions
option, then any trustlines
created by this account can have a ClawbackOp operation submitted for the
corresponding asset.
# constant AuthImmutableFlag
When set using Operation.setOptions
option, then none of the
authorization flags can be set and the account can never be deleted.
# constant AuthRequiredFlag
When set using Operation.setOptions
option, requires the issuing
account to give other accounts permission before they can hold the issuing
account’s credit.
# constant AuthRevocableFlag
When set using Operation.setOptions
option, allows the issuing
account to revoke its credit held by other accounts.
# constant BASE_FEE
Minimum base fee for transactions. If this fee is below the network minimum, the transaction will fail. The more operations in the transaction, the greater the required fee. Use Server#fetchBaseFee to get an accurate value of minimum transaction fee on the network.
# constant FastSigning
Use this flag to check if fast signing (provided by sodium-native
package) is available.
If your app is signing a large number of transaction or verifying a large number
of signatures make sure sodium-native
package is installed.
# LinearSleepStrategy
A function that returns the number of milliseconds to sleep
on a given iter
ation.
Object
# constant Networks
Contains passphrases for common networks:
Networks.PUBLIC
:Public Global Stellar Network ; September 2015
Networks.TESTNET
:Test SDF Network ; September 2015
Networks.FUTURENET
:Test SDF Future Network ; October 2022
Networks.STANDALONE
:Standalone Network ; February 2017
# constant TimeoutInfinite
Methods
# asciiCompare(a, b) → {number}
Compares two ASCII strings in lexographic order with uppercase precedence.
Parameters:
Name | Type | Description |
---|---|---|
a |
string
|
the first string to compare |
b |
string
|
the second |
like all compare()
s:
-1 if a < b
, 0 if a == b
, and 1 if a > b
number
# authorizeEntry(entry, signer, validUntilLedgerSeq, networkPassphraseopt) → {Promise.<xdr.SorobanAuthorizationEntry>}
Actually authorizes an existing authorization entry using the given the credentials and expiration details, returning a signed copy.
This "fills out" the authorization entry with a signature, indicating to the Operation.invokeHostFunction its attached to that:
- a particular identity (i.e. signing Keypair or other signer)
- approving the execution of an invocation tree (i.e. a simulation-acquired xdr.SorobanAuthorizedInvocation or otherwise built)
- on a particular network (uniquely identified by its passphrase, see Networks)
- until a particular ledger sequence is reached.
This one lets you pass a either a Keypair (or, more accurately,
anything with a sign(Buffer): Buffer
method) or a callback function (see
SigningCallback) to handle signing the envelope hash.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
entry |
xdr.SorobanAuthorizationEntry
|
an unsigned authorization entr |
|
signer |
Keypair
|
SigningCallback
|
either a Keypair instance
or a function which takes a payload (a
xdr.HashIdPreimageSorobanAuthorization instance) input and returns
the signature of the hash of the raw payload bytes (where the signing key
should correspond to the address in the |
|
validUntilLedgerSeq |
number
|
the (exclusive) future ledger sequence
number until which this authorization entry should be valid (if
|
|
networkPassphrase |
string
|
<optional> |
the network passphrase is incorprated into the signature (see Networks for options) |
a promise for an authorization entry that you can pass along to Operation.invokeHostFunction
Promise.<xdr.SorobanAuthorizationEntry>
Example
import {
SorobanRpc,
Transaction,
Networks,
authorizeEntry
} from '@stellar/stellar-sdk';
// Assume signPayloadCallback is a well-formed signing callback.
//
// It might, for example, pop up a modal from a browser extension, send the
// transaction to a third-party service for signing, or just do simple
// signing via Keypair like it does here:
function signPayloadCallback(payload) {
return signer.sign(hash(payload.toXDR());
}
function multiPartyAuth(
server: SorobanRpc.Server,
// assume this involves multi-party auth
tx: Transaction,
) {
return server
.simulateTransaction(tx)
.then((simResult) => {
tx.operations[0].auth.map(entry =>
authorizeEntry(
entry,
signPayloadCallback,
currentLedger + 1000,
Networks.TESTNET);
));
return server.prepareTransaction(tx, simResult);
})
.then((preppedTx) => {
preppedTx.sign(source);
return server.sendTransaction(preppedTx);
});
}
# authorizeInvocation(signer, validUntilLedgerSeq, invocation, publicKeyopt, networkPassphraseopt) → {Promise.<xdr.SorobanAuthorizationEntry>}
This builds an entry from scratch, allowing you to express authorization as a function of:
- a particular identity (i.e. signing Keypair or other signer)
- approving the execution of an invocation tree (i.e. a simulation-acquired xdr.SorobanAuthorizedInvocation or otherwise built)
- on a particular network (uniquely identified by its passphrase, see Networks)
- until a particular ledger sequence is reached.
This is in contrast to authorizeEntry, which signs an existing entry.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
signer |
Keypair
|
SigningCallback
|
either a Keypair instance
(or anything with a |
|
validUntilLedgerSeq |
number
|
the (exclusive) future ledger sequence
number until which this authorization entry should be valid (if
|
|
invocation |
xdr.SorobanAuthorizedInvocation
|
the invocation tree that we're authorizing (likely, this comes from transaction simulation) |
|
publicKey |
string
|
<optional> |
the public identity of the signer (when
providing a Keypair to |
networkPassphrase |
string
|
<optional> |
the network passphrase is incorprated into the signature (see Networks for options, default: Networks.FUTURENET) |
a promise for an authorization entry that you can pass along to Operation.invokeHostFunction
Promise.<xdr.SorobanAuthorizationEntry>
# buildInvocationTree(root) → {InvocationTree}
Turns a raw invocation tree into a human-readable format.
This is designed to make the invocation tree easier to understand in order to inform users about the side-effects of their contract calls. This will help make informed decisions about whether or not a particular invocation will result in what you expect it to.
Parameters:
Name | Type | Description |
---|---|---|
root |
xdr.SorobanAuthorizedInvocation
|
the raw XDR of the invocation,
likely acquired from transaction simulation. this is either from the
Operation.invokeHostFunction itself (the |
a human-readable version of the invocation tree
Example
Here, we show a browser modal after simulating an arbitrary transaction,
`tx`, which we assume has an `Operation.invokeHostFunction` inside of it:
```typescript
import { Server, buildInvocationTree } from '@stellar/stellar-sdk';
const s = new Server("fill in accordingly");
s.simulateTransaction(tx).then(
(resp: SorobanRpc.SimulateTransactionResponse) => {
if (SorobanRpc.isSuccessfulSim(resp) && ) {
// bold assumption: there's a valid result with an auth entry
alert(
"You are authorizing the following invocation:\n" +
JSON.stringify(
buildInvocationTree(resp.result!.auth[0].rootInvocation()),
null,
2
)
);
}
}
);
```
# decodeAddressToMuxedAccount(address) → {xdr.MuxedAccount}
Converts a Stellar address (in G... or M... form) to an xdr.MuxedAccount
structure, using the ed25519 representation when possible.
This supports full muxed accounts, where an M...
address will resolve to
both its underlying G...
address and an integer ID.
Parameters:
Name | Type | Description |
---|---|---|
address |
string
|
G... or M... address to encode into XDR |
a muxed account object for this address string
xdr.MuxedAccount
# encodeMuxedAccount(address, id) → {xdr.MuxedAccount}
Transform a Stellar address (G...) and an ID into its XDR representation.
Parameters:
Name | Type | Description |
---|---|---|
address |
string
|
a Stellar G... address |
id |
string
|
a Uint64 ID represented as a string |
- XDR representation of the above muxed account
xdr.MuxedAccount
# encodeMuxedAccountToAddress(muxedAccount) → {string}
Converts an xdr.MuxedAccount to its StrKey representation.
This returns its "M..." string representation if there is a muxing ID within the object and returns the "G..." representation otherwise.
Parameters:
Name | Type | Description |
---|---|---|
muxedAccount |
xdr.MuxedAccount
|
Raw account to stringify |
Stringified G... (corresponding to the underlying pubkey) or M... address (corresponding to both the key and the muxed ID)
string
# extractBaseAddress(address) → {string}
Extracts the underlying base (G...) address from an M-address.
Parameters:
Name | Type | Description |
---|---|---|
address |
string
|
an account address (either M... or G...) |
a Stellar public key address (G...)
string
# getLiquidityPoolId(liquidityPoolType, liquidityPoolParameters) → {Buffer}
getLiquidityPoolId computes the Pool ID for the given assets, fee and pool type.
Parameters:
Name | Type | Description |
---|---|---|
liquidityPoolType |
string
|
– A string representing the liquidity pool type. |
liquidityPoolParameters |
object
|
– The liquidity pool parameters. |
assetA |
Asset
|
– The first asset in the Pool, it must respect the rule assetA < assetB. |
assetB |
Asset
|
– The second asset in the Pool, it must respect the rule assetA < assetB. |
fee |
number
|
– The liquidity pool fee. For now the only fee supported is |
the raw Pool ID buffer, which can be stringfied with toString('hex')
Buffer
# getSalty() → {Buffer}
a random 256-bit "salt" value.
Buffer
# humanizeEvents(events) → {Array.<SorobanEvent>}
Converts raw diagnostic or contract events into something with a flatter, human-readable, and understandable structure.
Parameters:
Name | Type | Description |
---|---|---|
events |
Array.<xdr.DiagnosticEvent>
|
Array.<xdr.ContractEvent>
|
either contract events or diagnostic events to parse into a friendly format |
a list of human-readable event structures, where each element has the following properties:
- type: a string of one of 'system', 'contract', 'diagnostic
- contractId?: optionally, a
C...
encoded strkey - topics: a list of scValToNative invocations on the topics
- data: similarly, a scValToNative invocation on the raw event data
Array.<SorobanEvent>
# isValid(versionByteName, encoded) → {Boolean}
Sanity-checks whether or not a strkey appears valid.
Parameters:
Name | Type | Description |
---|---|---|
versionByteName |
string
|
the type of strkey to expect in |
encoded |
string
|
the strkey to validate |
whether or not the encoded
strkey appears valid for the
versionByteName
strkey type (see versionBytes
, above).
Boolean
# isValidDate(d) → {boolean}
Checks whether a provided object is a valid Date.
Parameters:
Name | Type | Description |
---|---|---|
d |
Date
|
date object |
boolean
# nativeToScVal(val, optsopt) → {xdr.ScVal}
Attempts to convert native types into smart contract values (xdr.ScVal).
Provides conversions from smart contract XDR values (xdr.ScVal) to native JavaScript types.
The conversions are as follows:
-
xdr.ScVal -> passthrough
-
null/undefined -> scvVoid
-
string -> scvString (a copy is made)
-
UintArray8 -> scvBytes (a copy is made)
-
boolean -> scvBool
-
number/bigint -> the smallest possible XDR integer type that will fit the input value (if you want a specific type, use ScInt)
-
Address or Contract -> scvAddress (for contracts and public keys)
-
Array
-> scvVec after attempting to convert each item of type T
to an xdr.ScVal (recursively). note that all values must be the same type! -
object -> scvMap after attempting to convert each key and value to an xdr.ScVal (recursively). note that there is no restriction on types matching anywhere (unlike arrays)
When passing an integer-like native value, you can also optionally specify a type which will force a particular interpretation of that value.
Note that not all type specifications are compatible with all ScVal
s, e.g.
toScVal("a string", {type: "i256"})
will throw.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
val |
any
|
a native (or convertible) input value to wrap |
|
opts |
object
|
<optional> |
an optional set of hints around the type of conversion you'd like to see |
type |
string
|
<optional> |
there is different behavior for different input
types for
As a simple example, |
if...
- there are arrays with more than one type in them
- there are values that do not have a sensible conversion (e.g. random XDR types, custom classes)
- the type of the input object (or some inner value of said object) cannot
be determined (via
typeof
) - the type you specified (via
opts.type
) is incompatible with the value you passed in (val
), e.g.nativeToScVal("a string", { type: 'i128' })
, though this does not apply for types that ignoreopts
(e.g. addresses).
TypeError
a wrapped, smart, XDR version of the input value
xdr.ScVal
Examples
nativeToScVal(1000); // gives ScValType === scvU64
nativeToScVal(1000n); // gives ScValType === scvU64
nativeToScVal(1n << 100n); // gives ScValType === scvU128
nativeToScVal(1000, { type: 'u32' }); // gives ScValType === scvU32
nativeToScVal(1000, { type: 'i125' }); // gives ScValType === scvI256
nativeToScVal("a string"); // gives ScValType === scvString
nativeToScVal("a string", { type: 'symbol' }); // gives scvSymbol
nativeToScVal(new Uint8Array(5)); // scvBytes
nativeToScVal(new Uint8Array(5), { type: 'symbol' }); // scvSymbol
nativeToScVal(null); // scvVoid
nativeToScVal(true); // scvBool
nativeToScVal([1, 2, 3]); // gives scvVec with each element as scvU64
nativeToScVal([1, 2, 3], { type: 'i128' }); // scvVec<scvI128>
nativeToScVal({ 'hello': 1, 'world': [ true, false ] }, {
type: {
'hello': [ 'symbol', 'i128' ],
}
})
// gives scvMap with entries: [
// [ scvSymbol, scvI128 ],
// [ scvString, scvArray<scvBool> ]
// ]
import {
nativeToScVal,
scValToNative,
ScInt,
xdr
} from '@stellar/stellar-base';
let gigaMap = {
bool: true,
void: null,
u32: xdr.ScVal.scvU32(1),
i32: xdr.ScVal.scvI32(1),
u64: 1n,
i64: -1n,
u128: new ScInt(1).toU128(),
i128: new ScInt(1).toI128(),
u256: new ScInt(1).toU256(),
i256: new ScInt(1).toI256(),
map: {
arbitrary: 1n,
nested: 'values',
etc: false
},
vec: ['same', 'type', 'list'],
};
// then, simply:
let scv = nativeToScVal(gigaMap); // scv.switch() == xdr.ScValType.scvMap()
// then...
someContract.call("method", scv);
// Similarly, the inverse should work:
scValToNative(scv) == gigaMap; // true
# scValToBigInt(scv) → {bigint}
Transforms an opaque xdr.ScVal into a native bigint, if possible.
If you then want to use this in the abstractions provided by this module, you can pass it to the constructor of XdrLargeInt.
Parameters:
Name | Type | Description |
---|---|---|
scv |
xdr.ScVal
|
the raw XDR value to parse into an integer |
if the scv
input value doesn't represent an integer
TypeError
the native value of this input value
bigint
Example
let scv = contract.call("add", x, y); // assume it returns an xdr.ScVal
let bigi = scValToBigInt(scv);
new ScInt(bigi); // if you don't care about types, and
new XdrLargeInt('i128', bigi); // if you do
# scValToNative(scv) → {any}
Given a smart contract value, attempt to convert it to a native type. Possible conversions include:
- void ->
null
- u32, i32 ->
number
- u64, i64, u128, i128, u256, i256 ->
bigint
- vec ->
Array
of any of the above (via recursion) - map -> key-value object of any of the above (via recursion)
- bool ->
boolean
- bytes ->
Uint8Array
- symbol ->
string
- string ->
string
IF the underlying buffer can be decoded as ascii/utf8,Uint8Array
of the raw contents in any error case
If no viable conversion can be determined, this just "unwraps" the smart value to return its underlying XDR value.
Parameters:
Name | Type | Description |
---|---|---|
scv |
xdr.ScVal
|
the input smart contract value |
any
# walkInvocationTree(root, callback) → {void}
Executes a callback function on each node in the tree until stopped.
Nodes are walked in a depth-first order. Returning false
from the callback
stops further depth exploration at that node, but it does not stop the walk
in a "global" view.
Parameters:
Name | Type | Description |
---|---|---|
root |
xdr.SorobanAuthorizedInvocation
|
the tree to explore |
callback |
InvocationWalker
|
the callback to execute for each node |
void
Type Definitions
# CreateInvocation
Properties:
Name | Type | Attributes | Description |
---|---|---|---|
type |
'wasm'
|
'sac'
|
a type indicating if this creation was a custom contract or a wrapping of an existing Stellar asset |
|
token |
string
|
<optional> |
when |
wasm |
object
|
<optional> |
when |
hash |
string
|
hex hash of WASM bytecode backing this contract |
|
address |
string
|
contract address of this deployment |
|
salt |
string
|
hex salt that the user consumed when creating this contract (encoded in the resulting address) |
|
constructorArgs |
Array.<any>
|
<optional> |
a list of natively-represented values (see scValToNative) that are passed to the constructor when creating this contract |
# ExecuteInvocation
Properties:
Name | Type | Description |
---|---|---|
source |
string
|
the strkey of the contract (C...) being invoked |
function |
string
|
the name of the function being invoked |
args |
Array.<any>
|
the natively-represented parameters to the function invocation (see scValToNative for rules on how they're represented a JS types) |
# InvocationTree
Properties:
Name | Type | Description |
---|---|---|
type |
'execute'
|
'create'
|
the type of invocation occurring, either contract creation or host function execution |
args |
CreateInvocation
|
ExecuteInvocation
|
the parameters to the invocation, depending on the type |
invocations |
Array.<InvocationTree>
|
any sub-invocations that (may) occur as a result of this invocation (i.e. a tree of call stacks) |
# InvocationWalker(node, depth, parentopt) → {boolean|null|void}
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
node |
xdr.SorobanAuthorizedInvocation
|
the currently explored node |
|
depth |
number
|
the depth of the tree this node is occurring at (the root starts at a depth of 1) |
|
parent |
xdr.SorobanAuthorizedInvocation
|
<optional> |
this |
returning exactly false
is a hint to stop
exploring, other values are ignored
boolean
|
null
|
void
# SignAuthEntry(authEntry, opts, authEntry, optsopt)
A function to request a wallet to sign an authorization entry preimage.
Similar to signing a transaction, this function takes an authorization entry preimage provided by the requester and applies a signature to it. It returns a signed hash of the same authorization entry and the signer address back to the requester.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
authEntry |
The authorization entry preimage to be signed. |
||
opts |
Options for signing the authorization entry. |
||
networkPassphrase |
The network's passphrase on which the authorization entry is intended to be signed. |
||
address |
The public key of the account that should be used to sign. |
||
authEntry |
string
|
||
opts |
object
|
<optional> |
A promise resolving to an object with the signed authorization entry and optional signer address and error.
# SignTransaction(xdr, opts, xdr, optsopt)
A function to request a wallet to sign a built transaction
This function takes an XDR provided by the requester and applies a signature to it. It returns a base64-encoded string XDR-encoded Transaction Envelope with Decorated Signatures and the signer address back to the requester.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
xdr |
The XDR string representing the transaction to be signed. |
||
opts |
Options for signing the transaction. |
||
networkPassphrase |
The network's passphrase on which the transaction is intended to be signed. |
||
address |
The public key of the account that should be used to sign. |
||
submit |
If set to true, submits the transaction immediately after signing. |
||
submitUrl |
The URL of the network to which the transaction should be submitted, if applicable. |
||
xdr |
string
|
||
opts |
object
|
<optional> |
A promise resolving to an object with the signed transaction XDR and optional signer address and error.
# async SigningCallback(preimage) → {Promise.<Uint8Array>}
Parameters:
Name | Type | Description |
---|---|---|
preimage |
xdr.HashIdPreimage
|
the entire authorization envelope whose hash you should sign, so that you can inspect the entire structure if necessary (rather than blindly signing a hash) |
the signature of the raw payload (which is
the sha256 hash of the preimage bytes, so hash(preimage.toXDR())
) signed
by the key corresponding to the public key in the entry you pass to
authorizeEntry (decipherable from its
credentials().address().address()
)
Promise.<Uint8Array>
# SleepStrategy(iter)
A function that returns the number of milliseconds to sleep
on a given iter
ation.
Parameters:
Name | Type | Description |
---|---|---|
iter |
number
|