Issue a Fungible Token
Anyone can issue various types of tokens in the XRP Ledger, ranging from informal "IOUs" to fiat-backed stablecoins, purely digital fungible and semi-fungible tokens, and more. This tutorial shows the technical steps of creating a token in the ledger. For more information on how XRP Ledger tokens work, see Issued Currencies; for more on the business decisions involved in issuing a stablecoin, see Become an XRP Ledger Gateway.
Prerequisites
- You need two funded XRP Ledger accounts, each with an address, secret key, and some XRP. For this tutorial, you can generate new test credentials as needed.
- Each address needs enough XRP to satisfy the reserve requirement including the additional reserve for a trust line.
- You need a connection to the XRP Ledger network. As shown in this tutorial, you can use public servers for testing.
- You should be familiar with the Getting Started instructions for your preferred client library. This page provides examples for the following:
- JavaScript with the xrpl.js library . See Get Started Using JavaScript for setup steps.
- Python with the
xrpl-py
library . See Get Started using Python for setup steps. - Java with the xrpl4j library . See Get Started Using Java for setup steps.
- You can also read along and use the interactive steps in your browser without any setup.
Example Code
Complete sample code for all of the steps of these tutorials is available under the MIT license .
- See Code Samples: Issue a Fungible Token in the source repository for this website.
Steps
1. Get Credentials
To transact on the XRP Ledger, you need an address and secret key, and some XRP. You also need one or more recipients who are willing to hold the tokens you issue: unlike in some other blockchains, in the XRP Ledger you cannot force someone to hold a token they do not want.
The best practice is to use "cold" and "hot" addresses. The cold address is the issuer of the token. The hot address is like a regular user's address that you control. It receives tokens from the cold address, which you can then transfer to other users. A hot address is not strictly necessary, since you could send tokens directly to users from the cold address, but it is good practice for security reasons. In production, you should take extra care of the cold address's cryptographic keys (for example, keeping them offline) because it is much harder to replace a cold address than a hot address.
In this tutorial, the hot address receives the tokens you issue from the cold address. You can get the keys for two addresses using the following interface.
Caution: Ripple provides the Testnet and Devnet for testing purposes only, and sometimes resets the state of these test networks along with all balances. As a precaution, do not use the same addresses on Testnet/Devnet and Mainnet.
When you're building production-ready software, you should use an existing account, and manage your keys using a secure signing configuration.
2. Connect to the Network
You must be connected to the network to submit transactions to it. The following code shows how to connect to a public XRP Ledger Testnet server with a supported client library:
// In browsers, use a <script> tag. In Node.js, uncomment the following line:
// const xrpl = require('xrpl')
// Wrap code in an async function so we can use await
async function main() {
// Define the network client
const client = new xrpl.Client("wss://s.altnet.rippletest.net:51233")
await client.connect()
// ... custom code goes here
// Disconnect when done (If you omit this, Node.js won't end the process)
client.disconnect()
}
main()
# Connect ----------------------------------------------------------------------
import xrpl
testnet_url = "https://s.altnet.rippletest.net:51234"
client = xrpl.clients.JsonRpcClient(testnet_url)
// Construct a network client ----------------------------------------------
HttpUrl rippledUrl = HttpUrl
.get("https://s.altnet.rippletest.net:51234/");
XrplClient xrplClient = new XrplClient(rippledUrl);
// Get the current network fee
FeeResult feeResult = xrplClient.fee();
Note: The JavaScript code samples in this tutorial use the async
/await
pattern . Since await
needs to be used from within an async
function, the remaining code samples are written to continue inside the main()
function started here. You can also use Promise methods .then()
and .catch()
instead of async
/await
if you prefer.
For this tutorial, click the following button to connect:
3. Configure Issuer Settings
First, configure the settings for your cold address (which will become the issuer of your token). Most settings can be reconfigured later, with the following exceptions:
- Default Ripple: This setting is required so that users can send your token to each other. It's best to enable it before setting up any trust lines or issuing any tokens.
- Authorized Trust Lines: (Optional) This setting (also called "Require Auth") limits your tokens to being held only by accounts you've explicitly approved. You cannot enable this setting if you already have any trust lines or offers for any token. Note: To use authorized trust lines, you must perform additional steps that are not shown in this tutorial.
Other settings you may want to, optionally, configure for your cold address (issuer):
Setting | Recommended Value | Summary |
---|---|---|
Require Destination Tags | Enabled or Disabled | Enable if you process withdrawals of your token to outside systems. (For example, your token is a stablecoin.) |
Disallow XRP | Enabled or Disabled | Enable if this address isn't meant to process XRP payments. |
Transfer Fee | 0–1% | Charge a percentage fee when users send your token to each other. |
Tick Size | 5 | Limit the number of decimal places in exchange rates for your token in the decentralized exchange. A tick size of 5-6 reduces churn of almost-equivalent offers and speeds up price discovery compared to the default of 15. |
Domain | (Your domain name) | Set to a domain you own so can verify ownership of the accounts. This can help reduce confusion or impersonation attempts. |
You can change these settings later as well.
Note: Many issuing settings apply equally to all tokens issued by an address, regardless of the currency code. If you want to issue multiple types of tokens in the XRP Ledger with different settings, you should use a different address to issue each different token.
The following code sample shows how to send an AccountSet transaction to enable the recommended cold address settings:
// Configure issuer (cold address) settings ----------------------------------
const cold_settings_tx = {
"TransactionType": "AccountSet",
"Account": cold_wallet.address,
"TransferRate": 0,
"TickSize": 5,
"Domain": "6578616D706C652E636F6D", // "example.com"
"SetFlag": xrpl.AccountSetAsfFlags.asfDefaultRipple,
// Using tf flags, we can enable more flags in one transaction
"Flags": (xrpl.AccountSetTfFlags.tfDisallowXRP |
xrpl.AccountSetTfFlags.tfRequireDestTag)
}
const cst_prepared = await client.autofill(cold_settings_tx)
const cst_signed = cold_wallet.sign(cst_prepared)
console.log("Sending cold address AccountSet transaction...")
const cst_result = await client.submitAndWait(cst_signed.tx_blob)
if (cst_result.result.meta.TransactionResult == "tesSUCCESS") {
console.log(`Transaction succeeded: https://testnet.xrpl.org/transactions/${cst_signed.hash}`)
} else {
throw `Error sending transaction: ${cst_result}`
}
# Configure issuer (cold address) settings -------------------------------------
cold_settings_tx = xrpl.models.transactions.AccountSet(
account=cold_wallet.classic_address,
transfer_rate=0,
tick_size=5,
domain=bytes.hex("example.com".encode("ASCII")),
set_flag=xrpl.models.transactions.AccountSetFlag.ASF_DEFAULT_RIPPLE,
)
cst_prepared = xrpl.transaction.safe_sign_and_autofill_transaction(
transaction=cold_settings_tx,
wallet=cold_wallet,
client=client,
)
print("Sending cold address AccountSet transaction...")
response = xrpl.transaction.send_reliable_submission(cst_prepared, client)
print(response)
// Configure issuer settings -----------------------------------------------
UnsignedInteger coldWalletSequence = xrplClient.accountInfo(
AccountInfoRequestParams.builder()
.ledgerIndex(LedgerIndex.CURRENT)
.account(coldWallet.classicAddress())
.build()
).accountData().sequence();
AccountSet setDefaultRipple = AccountSet.builder()
.account(coldWallet.classicAddress())
.fee(feeResult.drops().minimumFee())
.sequence(coldWalletSequence)
.signingPublicKey(coldWallet.publicKey())
.setFlag(AccountSet.AccountSetFlag.DEFAULT_RIPPLE)
.lastLedgerSequence(computeLastLedgerSequence(xrplClient))
.build();
PrivateKey coldWalletPrivateKey = PrivateKey.fromBase16EncodedPrivateKey(
coldWallet.privateKey().get()
);
SignatureService coldWalletSignatureService = new SingleKeySignatureService(coldWalletPrivateKey);
SignedTransaction<AccountSet> signedSetDefaultRipple = coldWalletSignatureService.sign(
KeyMetadata.EMPTY,
setDefaultRipple
);
submitAndWaitForValidation(signedSetDefaultRipple, xrplClient);
4. Wait for Validation
Most transactions are accepted into the next ledger version after they're submitted, which means it may take 4-7 seconds for a transaction's outcome to be final. You should wait for your earlier transactions to be fully validated before proceeding to the later steps, to avoid unexpected failures from things executing out of order. For more information, see Reliable Transaction Submission.
The code samples in this tutorial use helper functions to wait for validation when submitting a transaction:
- JavaScript: The
submit_and_verify()
function, as defined in the submit-and-verify code sample . - Python: The
send_reliable_submission()
method of the xrpl-py library . - Java: The
submitAndWaitForValidation()
method in the sample Java class .
Tip: Technically, you can configure the hot address in parallel with configuring the issuer address. For simplicity, this tutorial waits for each transaction one at a time.
Transaction ID: | (None) |
---|---|
Latest Validated Ledger Index: | (Not connected) |
Ledger Index at Time of Submission: | (Not submitted) |
Transaction LastLedgerSequence : |
(Not prepared) |
5. Configure Hot Address Settings
The hot address does not strictly require any settings changes from the default, but the following are recommended as best practices:
Setting | Recommended Value | Summary |
---|---|---|
Default Ripple | Disabled | Leave this setting disabled. (This is the default.) |
Authorized Trust Lines | Enabled | Enable this setting on the hot address—and never approve any trust lines to the hot address—to prevent accidentally issuing tokens from the wrong address. (Optional, but recommended.) |
Require Destination Tags | Enabled or Disabled | Enable if you process withdrawals of your token to outside systems. (For example, your token is a stablecoin.) |
Disallow XRP | Enabled or Disabled | Enable if this address isn't meant to process XRP payments. |
Domain | (Your domain name) | Set to a domain you own so can verify ownership of the accounts. This can help reduce confusion or impersonation attempts. |
The following code sample shows how to send an AccountSet transaction to enable the recommended hot address settings:
// Configure hot address settings --------------------------------------------
const hot_settings_tx = {
"TransactionType": "AccountSet",
"Account": hot_wallet.address,
"Domain": "6578616D706C652E636F6D", // "example.com"
// enable Require Auth so we can't use trust lines that users
// make to the hot address, even by accident:
"SetFlag": xrpl.AccountSetAsfFlags.asfRequireAuth,
"Flags": (xrpl.AccountSetTfFlags.tfDisallowXRP |
xrpl.AccountSetTfFlags.tfRequireDestTag)
}
const hst_prepared = await client.autofill(hot_settings_tx)
const hst_signed = hot_wallet.sign(hst_prepared)
console.log("Sending hot address AccountSet transaction...")
const hst_result = await client.submitAndWait(hst_signed.tx_blob)
if (hst_result.result.meta.TransactionResult == "tesSUCCESS") {
console.log(`Transaction succeeded: https://testnet.xrpl.org/transactions/${hst_signed.hash}`)
} else {
throw `Error sending transaction: ${hst_result.result.meta.TransactionResult}`
}
# Configure hot address settings -----------------------------------------------
hot_settings_tx = xrpl.models.transactions.AccountSet(
account=hot_wallet.classic_address,
set_flag=xrpl.models.transactions.AccountSetFlag.ASF_REQUIRE_AUTH,
)
hst_prepared = xrpl.transaction.safe_sign_and_autofill_transaction(
transaction=hot_settings_tx,
wallet=hot_wallet,
client=client,
)
print("Sending hot address AccountSet transaction...")
response = xrpl.transaction.send_reliable_submission(hst_prepared, client)
print(response)
// Configure hot address settings ------------------------------------------
UnsignedInteger hotWalletSequence = xrplClient.accountInfo(
AccountInfoRequestParams.builder()
.ledgerIndex(LedgerIndex.CURRENT)
.account(hotWallet.classicAddress())
.build()
).accountData().sequence();
AccountSet setRequireAuth = AccountSet.builder()
.account(hotWallet.classicAddress())
.fee(feeResult.drops().minimumFee())
.sequence(hotWalletSequence)
.signingPublicKey(hotWallet.publicKey())
.setFlag(AccountSet.AccountSetFlag.REQUIRE_AUTH)
.lastLedgerSequence(computeLastLedgerSequence(xrplClient))
.build();
PrivateKey hotWalletPrivateKey = PrivateKey.fromBase16EncodedPrivateKey(
hotWallet.privateKey().get()
);
SignatureService hotWalletSignatureService = new SingleKeySignatureService(hotWalletPrivateKey);
SignedTransaction<AccountSet> signedSetRequireAuth = hotWalletSignatureService.sign(
KeyMetadata.EMPTY,
setRequireAuth
);
submitAndWaitForValidation(signedSetRequireAuth, xrplClient);
6. Wait for Validation
As before, wait for the previous transaction to be validated by consensus before continuing.
Transaction ID: | (None) |
---|---|
Latest Validated Ledger Index: | (Not connected) |
Ledger Index at Time of Submission: | (Not submitted) |
Transaction LastLedgerSequence : |
(Not prepared) |
7. Create Trust Line from Hot to Cold Address
Before you can receive tokens, you need to create a trust line to the token issuer. This trust line is specific to the currency code of the token you want to issue, such as USD or FOO. You can choose any currency code you want; each issuer's tokens are treated as separate in the XRP Ledger protocol. However, users' balances of tokens with the same currency code can ripple between different issuers if the users enable rippling settings.
The hot address needs a trust line like this before it can receive tokens from the issuer. Similarly, each user who wants to hold your token must also create a trust line¹. Each trust line increases the reserve requirement of the hot address, so you must hold enough spare XRP to pay for the increased requirement. Your reserve requirement goes back down if you remove the trust line.
Tip: A trust line has a "limit" on how much the recipient is willing to hold; others cannot send you more tokens than your specified limit. For community credit systems, you may want to configure limits per individual based on how much you trust that person. For other types and uses of tokens, it is normally OK to set the limit to a very large number.
To create a trust line, send a TrustSet transaction from the hot address with the following fields:
Field | Value |
---|---|
TransactionType |
"TrustSet" |
Account |
The hot address. (More generally, this is the account that wants to receive the token.) |
LimitAmount |
An object specifying how much, of which token, from which issuer, you are willing to hold. |
LimitAmount.currency |
The currency code of the token. |
LimitAmount.issuer |
The cold address. |
LimitAmount.value |
The maximum amount of the token you are willing to hold. |
The following code sample shows how to send a TrustSet transaction from the hot address, trusting the issuing address for a limit of 1 billion FOO:
// Create trust line from hot to cold address --------------------------------
const currency_code = "FOO"
const trust_set_tx = {
"TransactionType": "TrustSet",
"Account": hot_wallet.address,
"LimitAmount": {
"currency": currency_code,
"issuer": cold_wallet.address,
"value": "10000000000" // Large limit, arbitrarily chosen
}
}
const ts_prepared = await client.autofill(trust_set_tx)
const ts_signed = hot_wallet.sign(ts_prepared)
console.log("Creating trust line from hot address to issuer...")
const ts_result = await client.submitAndWait(ts_signed.tx_blob)
if (ts_result.result.meta.TransactionResult == "tesSUCCESS") {
console.log(`Transaction succeeded: https://testnet.xrpl.org/transactions/${ts_signed.hash}`)
} else {
throw `Error sending transaction: ${ts_result.result.meta.TransactionResult}`
}
# Create trust line from hot to cold address -----------------------------------
currency_code = "FOO"
trust_set_tx = xrpl.models.transactions.TrustSet(
account=hot_wallet.classic_address,
limit_amount=xrpl.models.amounts.issued_currency_amount.IssuedCurrencyAmount(
currency=currency_code,
issuer=cold_wallet.classic_address,
value="10000000000", # Large limit, arbitrarily chosen
)
)
ts_prepared = xrpl.transaction.safe_sign_and_autofill_transaction(
transaction=trust_set_tx,
wallet=hot_wallet,
client=client,
)
print("Creating trust line from hot address to issuer...")
response = xrpl.transaction.send_reliable_submission(ts_prepared, client)
print(response)
// Create trust line -------------------------------------------------------
String currencyCode = "FOO";
ImmutableTrustSet trustSet = TrustSet.builder()
.account(hotWallet.classicAddress())
.fee(feeResult.drops().openLedgerFee())
.sequence(hotWalletSequence.plus(UnsignedInteger.ONE))
.limitAmount(IssuedCurrencyAmount.builder()
.currency(currencyCode)
.issuer(coldWallet.classicAddress())
.value("10000000000")
.build())
.signingPublicKey(hotWallet.publicKey())
.build();
SignedTransaction<TrustSet> signedTrustSet = hotWalletSignatureService.sign(
KeyMetadata.EMPTY,
trustSet
);
submitAndWaitForValidation(signedTrustSet, xrplClient);
Note: If you use Authorized Trust Lines, there is an extra step after this one: the cold address must approve the trust line from the hot address. For details of how to do this, see Authorizing Trust Lines.
8. Wait for Validation
As before, wait for the previous transaction to be validated by consensus before continuing.
Transaction ID: | (None) |
---|---|
Latest Validated Ledger Index: | (Not connected) |
Ledger Index at Time of Submission: | (Not submitted) |
Transaction LastLedgerSequence : |
(Not prepared) |
9. Send Token
Now you can create tokens by sending a Payment transaction from the cold address to the hot address. This transaction should have the following attributes (dot notation indicates nested fields):
Field | Value |
---|---|
TransactionType |
"Payment" |
Account |
The cold address issuing the token. |
Amount |
An token amount specifying how much of which token to create. |
Amount.currency |
The currency code of the token. |
Amount.value |
Decimal amount of the token to issue, as a string. |
Amount.issuer |
The cold address issuing the token. |
Destination |
The hot address (or other account receiving the token) |
Paths |
Omit this field when issuing tokens. |
SendMax |
Omit this field when issuing tokens. |
DestinationTag |
Any whole number from 0 to 232-1. You must specify something here if you enabled Require Destination Tags on the hot address. |
You can use auto-filled values for all other required fields.
The following code sample shows how to send a Payment transaction to issue 88 FOO from the cold address to the hot address:
// Send token ----------------------------------------------------------------
const issue_quantity = "3840"
const send_token_tx = {
"TransactionType": "Payment",
"Account": cold_wallet.address,
"Amount": {
"currency": currency_code,
"value": issue_quantity,
"issuer": cold_wallet.address
},
"Destination": hot_wallet.address,
"DestinationTag": 1 // Needed since we enabled Require Destination Tags
// on the hot account earlier.
}
const pay_prepared = await client.autofill(send_token_tx)
const pay_signed = cold_wallet.sign(pay_prepared)
console.log(`Sending ${issue_quantity} ${currency_code} to ${hot_wallet.address}...`)
const pay_result = await client.submitAndWait(pay_signed.tx_blob)
if (pay_result.result.meta.TransactionResult == "tesSUCCESS") {
console.log(`Transaction succeeded: https://testnet.xrpl.org/transactions/${pay_signed.hash}`)
} else {
throw `Error sending transaction: ${pay_result.result.meta.TransactionResult}`
}
# Send token -------------------------------------------------------------------
issue_quantity = "3840"
send_token_tx = xrpl.models.transactions.Payment(
account=cold_wallet.classic_address,
destination=hot_wallet.classic_address,
amount=xrpl.models.amounts.issued_currency_amount.IssuedCurrencyAmount(
currency=currency_code,
issuer=cold_wallet.classic_address,
value=issue_quantity
)
)
pay_prepared = xrpl.transaction.safe_sign_and_autofill_transaction(
transaction=send_token_tx,
wallet=cold_wallet,
client=client,
)
print(f"Sending {issue_quantity} {currency_code} to {hot_wallet.classic_address}...")
response = xrpl.transaction.send_reliable_submission(pay_prepared, client)
print(response)
// Send token --------------------------------------------------------------
Payment payment = Payment.builder()
.account(coldWallet.classicAddress())
.fee(feeResult.drops().openLedgerFee())
.sequence(coldWalletSequence.plus(UnsignedInteger.ONE))
.destination(hotWallet.classicAddress())
.amount(IssuedCurrencyAmount.builder()
.issuer(coldWallet.classicAddress())
.currency(currencyCode)
.value("3840")
.build())
.signingPublicKey(coldWallet.publicKey())
.build();
SignedTransaction<Payment> signedPayment = coldWalletSignatureService.sign(
KeyMetadata.EMPTY,
payment
);
submitAndWaitForValidation(signedPayment, xrplClient);
10. Wait for Validation
As before, wait for the previous transaction to be validated by consensus before continuing.
Transaction ID: | (None) |
---|---|
Latest Validated Ledger Index: | (Not connected) |
Ledger Index at Time of Submission: | (Not submitted) |
Transaction LastLedgerSequence : |
(Not prepared) |
11. Confirm Token Balances
You can check the balances of your token from the perspective of either the token issuer or the hot address. Tokens issued in the XRP Ledger always have balances that sum to 0: negative from the perspective of the issuer and positive from the perspective of the holder.
Use the account_lines method to look up the balances from the perspective of the holder. This lists each trust line along with its limit, balance, and settings.
Use the gateway_balances method to look up balances from the perspective of a token issuer. This provides a sum of all tokens issued by a given address.
Tip: Since the XRP Ledger is fully public, you can check the balances of any account at any time without needing any cryptographic keys.
The following code sample shows how to use both methods:
// Check balances ------------------------------------------------------------
console.log("Getting hot address balances...")
const hot_balances = await client.request({
command: "account_lines",
account: hot_wallet.address,
ledger_index: "validated"
})
console.log(hot_balances.result)
console.log("Getting cold address balances...")
const cold_balances = await client.request({
command: "gateway_balances",
account: cold_wallet.address,
ledger_index: "validated",
hotwallet: [hot_wallet.address]
})
console.log(JSON.stringify(cold_balances.result, null, 2))
client.disconnect()
}
# Check balances ---------------------------------------------------------------
print("Getting hot address balances...")
response = client.request(xrpl.models.requests.AccountLines(
account=hot_wallet.classic_address,
ledger_index="validated",
))
print(response)
print("Getting cold address balances...")
response = client.request(xrpl.models.requests.GatewayBalances(
account=cold_wallet.classic_address,
ledger_index="validated",
hotwallet=[hot_wallet.classic_address]
))
print(response)
// Check balances ----------------------------------------------------------
List<TrustLine> lines = xrplClient.accountLines(
AccountLinesRequestParams.builder()
.account(hotWallet.classicAddress())
.ledgerIndex(LedgerIndex.VALIDATED)
.build()
).lines();
System.out.println("Hot wallet TrustLines: " + lines);
}
Next Steps
Now that you've created the token, you can explore how it fits into features of the XRP Ledger:
- Send tokens from the hot address to other users.
- Trade it in the decentralized exchange.
- Monitor for incoming payments of your token.
- Create an xrp-ledger.toml file and set up domain verification for your token's issuer.
- Learn about other features of XRP Ledger tokens.
Footnotes
¹ Users can hold your token without explicitly creating a trust line if they buy your token in the decentralized exchange. Buying a token in the exchange automatically creates the necessary trust lines. This is only possible if someone is selling your token in the decentralized exchange.