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.
- Source:
- See:
(constant) AuthImmutableFlag
When set using Operation.setOptions
option, then none of the
authorization flags can be set and the account can never be deleted.
- Source:
- See:
(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.
- Source:
- See:
(constant) AuthRevocableFlag
When set using Operation.setOptions
option, allows the issuing
account to revoke its credit held by other accounts.
- Source:
- See:
(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.
- Source:
- See:
(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.
- Source:
(constant) Networks :Object
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
- Source:
Type:
-
Object
(constant) TimeoutInfinite
- Source:
- See:
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 |
Returns:
- Type:
-
number
like all compare()
s:
-1 if a < b
, 0 if a == b
, and 1 if a > b
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.
- Source:
- See:
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) |
Returns:
- Type:
-
Promise.<xdr.SorobanAuthorizationEntry>
a promise for an authorization entry that you can pass along to Operation.invokeHostFunction
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.
- Source:
- See:
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) |
Returns:
- Type:
-
Promise.<xdr.SorobanAuthorizationEntry>
a promise for an authorization entry that you can pass along to Operation.invokeHostFunction
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.
- Source:
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 |
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 |
Returns:
- Type:
-
xdr.MuxedAccount
a muxed account object for this address string
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 |
Returns:
- Type:
-
xdr.MuxedAccount
- XDR representation of the above muxed account
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 |
Returns:
- Type:
-
string
Stringified G... (corresponding to the underlying pubkey) or M... address (corresponding to both the key and the muxed ID)
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...) |
Returns:
- Type:
-
string
a Stellar public key address (G...)
getLiquidityPoolId(liquidityPoolType, liquidityPoolParameters) → {Buffer}
getLiquidityPoolId computes the Pool ID for the given assets, fee and pool type.
- Source:
- See:
Parameters:
Name | Type | Description | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
liquidityPoolType |
string
|
– A string representing the liquidity pool type. |
||||||||||||
liquidityPoolParameters |
object
|
– The liquidity pool parameters.
|
Returns:
- Type:
-
Buffer
the raw Pool ID buffer, which can be stringfied with toString('hex')
getSalty() → {Buffer}
Returns:
- Type:
-
Buffer
a random 256-bit "salt" value.
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 |
Returns:
- Type:
-
Array.<SorobanEvent>
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
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 |
Returns:
- Type:
-
Boolean
whether or not the encoded
strkey appears valid for the
versionByteName
strkey type (see versionBytes
, above).
isValidDate(d) → {boolean}
Checks whether a provided object is a valid Date.
- Source:
Parameters:
Name | Type | Description |
---|---|---|
d |
Date
|
date object |
Returns:
- Type:
-
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.
- Source:
- See:
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
|
Throws:
-
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).
- Type
-
TypeError
Returns:
- Type:
-
xdr.ScVal
a wrapped, smart, XDR version of the input value
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.
- Source:
Parameters:
Name | Type | Description |
---|---|---|
scv |
xdr.ScVal
|
the raw XDR value to parse into an integer |
Throws:
-
if the
scv
input value doesn't represent an integer - Type
-
TypeError
Returns:
- Type:
-
bigint
the native value of this input value
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.
- Source:
- See:
Parameters:
Name | Type | Description |
---|---|---|
scv |
xdr.ScVal
|
the input smart contract value |
Returns:
- Type:
-
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.
- Source:
Parameters:
Name | Type | Description |
---|---|---|
root |
xdr.SorobanAuthorizedInvocation
|
the tree to explore |
callback |
InvocationWalker
|
the callback to execute for each node |
Returns:
- Type:
-
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 |
||||||||||||||||
Name | Type | Attributes | Description |
---|---|---|---|
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 |
- Source:
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) |
- Source:
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) |
- Source:
InvocationWalker(node, depth, parentopt) → {boolean|null|void}
- Source:
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 |
Returns:
- Type:
-
boolean
|null
|void
returning exactly false
is a hint to stop
exploring, other values are ignored
(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) |
Returns:
- Type:
-
Promise.<Uint8Array>
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()
)