| title | Clawbacks |
|---|---|
| sidebar_position | 30 |
import { CodeExample } from "@site/src/components/CodeExample";
Clawbacks let an asset issuer burn a specific amount of a clawback-enabled asset. Introduced in CAP-0035, issuers can clawback from account trustlines or claimable balances. Clawbacks effectively destroy the assets by removing them from a recipient’s balance.
They allow asset issuers or their designated transfer agent to meet securities regulations; which in many jurisdictions requires the ability to revoke assets in the event of a mistake, fraudulent transaction, or other regulatory action regarding a specific person or asset.
Clawbacks are useful for:
- Recovering assets that have been fraudulently obtained,
- Responding to regulatory actions, and
- Enabling identity-proofed persons to recover an enabled asset in the event of loss of key custody or theft.
The issuer sets up their account to enable clawbacks using the AUTH_CLAWBACK_ENABLED flag. This causes every subsequent trustline established from the account to have the TRUSTLINE_CLAWBACK_ENABLED_FLAG set automatically.
If an issuing account wants to set the AUTH_CLAWBACK_ENABLED_FLAG, it must have the AUTH_REVOCABLE_FLAG set. This allows an asset issuer to claw back balances locked up in offers by first revoking authorization from a trustline, which pulls all offers that involve that trustline. The issuer can then perform the clawback.
The issuing account uses this operation to claw back some or all of an asset. Once an account holds a particular asset for which clawbacks have been enabled, the issuing account can claw it back, burning it. You need to provide the asset, a quantity, and the account from which you’re clawing back the asset.
This operation claws back a claimable balance, returning the asset to the issuer account, burning it. You must claw back the entire claimable balance, not just part of it. Once a claimable balance has been claimed, use the regular clawback operation to claw it back.
Clawback claimable balances require the claimable balance ID.
Remove clawback capabilities on a specific trustline by removing the TRUSTLINE_CLAWBACK_ENABLED_FLAG via the SetTrustLineFlags operation.
You can only clear a flag, not set it. So clearing a clawback flag on a trustline is irreversible. This is done so that you don’t retroactively change the rules on your asset holders. If you’d like to enable clawbacks again, holders must reissue their trustlines.
Here we’ll cover the following approaches to clawing back an asset.
-
Example 1: Issuing account
$\mathcal{A}$ creates a clawback-enabled asset and sends it to Account$\mathcal{B}$ . Then,$\mathcal{B}$ sends that asset to Account$\mathcal{C}$ . Lastly,$\mathcal{A}$ will clawback the asset from$\mathcal{C}$ . -
Example 2:
$\mathcal{B}$ creates a claimable balance for$\mathcal{C}$ , and$\mathcal{A}$ claws back the new claimable balance. -
Example 3:
$\mathcal{A}$ issues a clawback-enabled asset to$\mathcal{B}$ . Then,$\mathcal{A}$ claws back some of the asset from$\mathcal{B}$ . Next,$\mathcal{A}$ removes the clawback enabled flag from the trustline and can no longer clawback the asset.
First, we’ll set up an account to enable clawbacks and issue an asset accordingly. Properly issuing an asset with separate issuer and distributor accounts is a little more involved. We’ll use a simpler method here as an example.
:::note
We first need to enable clawbacks and then establish trustlines since you cannot retroactively enable clawback on existing trustlines.
:::
from stellar_sdk import Server, Keypair, Asset, Network, TransactionBuilder, Operation
server = Server("https://horizon-testnet.stellar.org")
A = Keypair.from_secret("SAQLZCQA6AYUXK6JSKVPJ2MZ5K5IIABJOEQIG4RVBHX4PG2KMRKWXCHJ")
B = Keypair.from_secret("SAAY2H7SANIS3JLFBFPLJRTYNLUYH4UTROIKRVFI4FEYV4LDW5Y7HDZ4")
C = Keypair.from_secret("SCZANGBA5YHTNYVVV4C3U252E2B6P6F5T3U6MM63WBSBZATAQI3EBTQ4")
AstroToken = Asset("ClawbackCoin", A.public_key)
def enableClawback(account, keys):
tx = buildTx(account, keys, [
Operation.set_options(
set_flags=Operation.Flag.AUTH_CLAWBACK_ENABLED_FLAG | Operation.Flag.AUTH_REVOCABLE_FLAG
# Also add `revocable` for control over who can hold the asset.
)
])
return server.submit_transaction(tx)
def establishTrustline(recipient, key):
tx = buildTx(recipient, key, [
Operation.change_trust(
asset=AstroToken,
)
])
return server.submit_transaction(tx)
def getAccounts():
return [
server.load_account(A.public_key),
server.load_account(B.public_key),
server.load_account(C.public_key)
]
def preamble():
accounts = getAccounts()
accountA, accountB, accountC = accounts
enableClawback(accountA, A)
return establishTrustline(accountB, B), establishTrustline(accountC, C)
def buildTx(source, signer, ops):
tx = TransactionBuilder(
source,
network_passphrase = Network.TESTNET,
base_fee = Network.BASE_FEE
)
for op in ops:
tx.append_operation(op)
tx.set_timeout(3600)
tx = tx.build()
tx.sign(signer)
return tx
def showBalances(accounts):
for accs in accounts:
print(f"{accs.account_id}: {getBalance(accs)}")
def getBalance(account):
for balance in account.balances:
if(
balance["asset_type"] != "native" and
balance["asset_code"] == AstroToken.code and
balance["asset_issuer"] == AstroToken.issuer
):
return balance["balance"]
return "0"const sdk = require("stellar-sdk");
let server = new sdk.Server("https://horizon-testnet.stellar.org");
const A = sdk.Keypair.fromSecret(
"SAQLZCQA6AYUXK6JSKVPJ2MZ5K5IIABJOEQIG4RVBHX4PG2KMRKWXCHJ",
);
const B = sdk.Keypair.fromSecret(
"SAAY2H7SANIS3JLFBFPLJRTYNLUYH4UTROIKRVFI4FEYV4LDW5Y7HDZ4",
);
const C = sdk.Keypair.fromSecret(
"SCZANGBA5YHTNYVVV4C3U252E2B6P6F5T3U6MM63WBSBZATAQI3EBTQ4",
);
const AstroToken = new sdk.Asset("ClawbackCoin", A.publicKey());
// Enables AuthClawbackEnabledFlag on an account.
function enableClawback(account, keys) {
return server.submitTransaction(
buildTx(account, keys, [
sdk.Operation.setOptions({
setFlags: sdk.AuthClawbackEnabledFlag | sdk.AuthRevocableFlag,
// Also add `revocable` for control over who can hold the asset.
}),
]),
);
}
// Establishes a trustline for `recipient` for AstroToken (from above).
const establishTrustline = function (recipient, key) {
return server.submitTransaction(
buildTx(recipient, key, [
sdk.Operation.changeTrust({
asset: AstroToken,
}),
]),
);
};
// Retrieves latest account info for all accounts.
function getAccounts() {
return Promise.all([
server.loadAccount(A.publicKey()),
server.loadAccount(B.publicKey()),
server.loadAccount(C.publicKey()),
]);
}
// Enables clawback on A, and establishes trustlines from C, B -> A.
function preamble() {
return getAccounts().then(function (accounts) {
let [accountA, accountB, accountC] = accounts;
return enableClawback(accountA, A).then(
Promise.all([
establishTrustline(accountB, B),
establishTrustline(accountC, C),
]),
);
});
}
// Helps simplify creating & signing a transaction.
function buildTx(source, signer, ops) {
var tx = new StellarSdk.TransactionBuilder(source, {
fee: sdk.BASE_FEE,
networkPassphrase: StellarSdk.Networks.TESTNET,
});
ops.forEach((op) => tx.addOperation(op));
tx = tx.setTimeout(3600).build();
tx.sign(signer);
return tx;
}
// Prints the balances of a list of accounts.
function showBalances(accounts) {
accounts.forEach((acc) => {
console.log(`${acc.accountId()}: ${getBalance(acc)}`);
});
}
// Retrieves the balance of AstroToken in `account`.
function getBalance(account) {
const balances = account.balances.filter((balance) => {
return (
balance.asset_code == AstroToken.code &&
balance.asset_issuer == AstroToken.issuer
);
});
return balances.length > 0 ? balances[0].balance : "0";
}import org.stellar.sdk.*;
import org.stellar.sdk.requests.RequestBuilder;
import org.stellar.sdk.responses.AccountResponse;
import org.stellar.sdk.responses.SubmitTransactionResponse;
public class Clawback {
private static final Server server = new Server("https://horizon-testnet.stellar.org");
private static final KeyPair A = KeyPair.fromSecretSeed("SAQLZCQA6AYUXK6JSKVPJ2MZ5K5IIABJOEQIG4RVBHX4PG2KMRKWXCHJ");
private static final KeyPair B = KeyPair.fromSecretSeed("SAAY2H7SANIS3JLFBFPLJRTYNLUYH4UTROIKRVFI4FEYV4LDW5Y7HDZ4");
private static final KeyPair C = KeyPair.fromSecretSeed("SCZANGBA5YHTNYVVV4C3U252E2B6P6F5T3U6MM63WBSBZATAQI3EBTQ4");
private static final Asset AstroToken = Asset.createNonNativeAsset("ClawbackCoin", A.getAccountId());
public static void main(String[] args) throws IOException {
AccountResponse[] accounts = getAccounts();
AccountResponse accountA = accounts[0];
AccountResponse accountB = accounts[1];
AccountResponse accountC = accounts[2];
enableClawback(accountA, A);
establishTrustline(accountB, B);
establishTrustline(accountC, C);
}
// Enables AuthClawbackEnabledFlag on an account.
private static void enableClawback(AccountResponse account, KeyPair keys) throws IOException {
Transaction transaction = buildTx(account, keys, new Operation[]{
new SetOptionsOperation.Builder()
.setSetFlags(AccountFlag.AUTH_CLAWBACK_ENABLED_FLAG | AccountFlag.AUTH_REVOCABLE_FLAG)
// Also add `revocable` for control over who can hold the asset.
.build()
});
SubmitTransactionResponse response = server.submitTransaction(transaction);
System.out.println("Clawback enabled: " + response);
}
// Establishes a trustline for `recipient` for AstroToken (from above).
private static void establishTrustline(AccountResponse recipient, KeyPair key) throws IOException {
Transaction transaction = buildTx(recipient, key, new Operation[]{
new ChangeTrustOperation.Builder(AstroToken, "922337203685.4775807").build()
});
SubmitTransactionResponse response = server.submitTransaction(transaction);
System.out.println("Trustline established: " + response);
}
// Retrieves latest account info for all accounts.
private static AccountResponse[] getAccounts() throws IOException {
AccountResponse accountA = server.accounts().account(A.getAccountId());
AccountResponse accountB = server.accounts().account(B.getAccountId());
AccountResponse accountC = server.accounts().account(C.getAccountId());
return new AccountResponse[]{accountA, accountB, accountC};
}
// Helper method to build and sign a transaction
private static Transaction buildTx(AccountResponse source, KeyPair signer, Operation[] ops) {
Transaction.Builder txBuilder = new Transaction.Builder(source, Network.TESTNET)
.setTimeout(3600)
.setBaseFee(Transaction.MIN_BASE_FEE);
for (Operation op : ops) {
txBuilder.addOperation(op);
}
Transaction transaction = txBuilder.build();
transaction.sign(signer);
return transaction;
}
// Prints the balances of a list of accounts.
private static void showBalances(AccountResponse[] accounts) throws IOException {
for (AccountResponse account : accounts) {
System.out.println(
account.getAccountId() +
": " +
getBalance(account)
);
}
}
// Retrieves the balance of AstroToken in `account`.
private static String getBalance(AccountResponse account) {
for (AccountResponse.Balance balance : account.getBalances()) {
if (!balance.getAssetType().equals("native") &&
balance.getAssetCode().equals(AstroToken.getCode()) &&
balance.getAssetIssuer().equals(AstroToken.getIssuer())) {
return balance.getBalance();
}
}
return "0";
}
}package main
import (
"fmt"
"github.com/stellar/go/build"
"github.com/stellar/go/clients/horizonclient"
"github.com/stellar/go/keypair"
"github.com/stellar/go/network"
"github.com/stellar/go/protocols/horizon"
"github.com/stellar/go/txnbuild"
)
var client = horizonclient.DefaultTestNetClient
var (
A = keypair.MustParseFull("SAQLZCQA6AYUXK6JSKVPJ2MZ5K5IIABJOEQIG4RVBHX4PG2KMRKWXCHJ")
B = keypair.MustParseFull("SAAY2H7SANIS3JLFBFPLJRTYNLUYH4UTROIKRVFI4FEYV4LDW5Y7HDZ4")
C = keypair.MustParseFull("SCZANGBA5YHTNYVVV4C3U252E2B6P6F5T3U6MM63WBSBZATAQI3EBTQ4")
AstroToken = txnbuild.CreditAsset{Code: "ClawbackCoin", Issuer: A.Address()}
)
// Enables AuthClawbackEnabledFlag on an account.
func enableClawback(account horizon.Account, keys *keypair.Full) {
tx, err := buildTx(account, keys, []txnbuild.Operation{
&txnbuild.SetOptions{
SetFlags: []txnbuild.AccountFlag{
txnbuild.AuthClawbackEnabled,
txnbuild.AuthRevocable,
// Also add `revocable` for control over who can hold the asset.
},
},
})
check(err)
resp, err := client.SubmitTransaction(tx)
check(err)
fmt.Println("Clawback enabled:", resp)
}
// Establishes a trustline for `recipient` for AstroToken (from above).
func establishTrustline(recipient horizon.Account, key *keypair.Full) {
tx, err := buildTx(recipient, key, []txnbuild.Operation{
&txnbuild.ChangeTrust{
Line: AstroToken,
},
})
check(err)
resp, err := client.SubmitTransaction(tx)
check(err)
fmt.Println("Trustline established:", resp)
}
// Retrieves latest account info for all accounts.
func getAccounts() ([]horizon.Account, error) {
accountA, err := client.AccountDetail(
horizonclient.AccountRequest{
AccountID: A.Address(),
},
)
check(err)
accountB, err := client.AccountDetail(
horizonclient.AccountRequest{
AccountID: B.Address(),
},
)
check(err)
accountC, err := client.AccountDetail(
horizonclient.AccountRequest{
AccountID: C.Address(),
},
)
check(err)
return []horizon.Account{accountA, accountB, accountC}, nil
}
// Helper method to build and sign a transaction.
func buildTx(source horizon.Account, signer *keypair.Full, ops []txnbuild.Operation) (*txnbuild.Transaction, error) {
tx, err := txnbuild.NewTransaction(
txnbuild.TransactionParams{
SourceAccount: &source,
IncrementSequenceNum: true,
BaseFee: txnbuild.MinBaseFee,
Operations: ops,
Timebounds: txnbuild.NewTimeout(3600),
},
)
check(err)
tx, err = tx.Sign(network.TestNetworkPassphrase, signer)
check(err)
return tx, nil
}
// Enables clawback on A, and establishes trustlines from C, B -> A.
func main() {
accounts, err := getAccounts()
check(err)
accountA := accounts[0]
accountB := accounts[1]
accountC := accounts[2]
enableClawback(accountA, A)
establishTrustline(accountB, B)
establishTrustline(accountC, C)
}
// Prints the balances of a list of accounts.
func showBalances(accounts []horizon.Account) {
for _, acc := range accounts {
fmt.Printf(
"%s: %s\n",
acc.AccountID,
getBalance(acc),
)
}
}
// Retrieves the balance of AstroToken in `account`.
func getBalance(account horizon.Account) string {
for _, balance := range account.Balances {
if balance.Asset.Type != "native" &&
balance.Asset.Code == AstroToken.GetCode() &&
balance.Asset.Issuer == AstroToken.GetIssuer() {
return balance.Balance
}
}
return "0"
}With the shared setup code out of the way, we can now demonstrate how clawback works for payments. This example will highlight how the asset issuer holds control over their asset regardless of how it gets distributed to the world.
In our scenario, Account AstroToken; then,
# Make a payment to `toAccount` from `fromAccount` for `amount`.
def makePayment(toAccount, fromAccount, fromKey, amount):
tx = buildTx(fromAccount, fromKey, [
Operation.payment(
destination=toAccount.account_id,
asset=AstroToken,
amount=amount,
)
])
return server.submit_transaction(tx)
# Perform a clawback by `byAccount` of `amount` from `fromAccount`.
def doClawback(byAccount, byKey, fromAccount, amount):
tx = buildTx(byAccount, byKey, [
Operation.clawback(
from_=fromAccount.account_id,
asset=AstroToken,
amount=amount,
)
])
return server.submit_transaction(tx)// Make a payment to `toAccount` from `fromAccount` for `amount`.
function makePayment(toAccount, fromAccount, fromKey, amount) {
return server.submitTransaction(
buildTx(fromAccount, fromKey, [
sdk.Operation.payment({
destination: toAccount.accountId(),
asset: AstroToken, // defined in preamble
amount: amount,
}),
]),
);
}
// Perform a clawback by `byAccount` of `amount` from `fromAccount`.
function doClawback(byAccount, byKey, fromAccount, amount) {
return server.submitTransaction(
buildTx(byAccount, byKey, [
sdk.Operation.clawback({
from: fromAccount.accountId(),
asset: AstroToken, // defined in preamble
amount: amount,
}),
]),
);
}// Make a payment to `toAccount` from `fromAccount` for `amount`.
private static void makePayment(AccountResponse toAccount, AccountResponse fromAccount, KeyPair fromKey, String amount) throws IOException {
Transaction tx = buildTx(fromAccount, fromKey, new Operation[]{
new PaymentOperation.Builder(
toAccount.getAccountId(),
AstroToken,
amount
).build()
});
SubmitTransactionResponse response = server.submitTransaction(tx);
}
// Perform a clawback by `byAccount` of `amount` from `fromAccount`.
private static void doClawback(AccountResponse byAccount, KeyPair byKey, AccountResponse fromAccount, String amount) throws IOException {
Transaction tx = buildTx(byAccount, byKey, new Operation[]{
new ClawbackOperation.Builder(
AstroToken,
fromAccount.getAccountId(),
amount
).build()
});
SubmitTransactionResponse response = server.submitTransaction(tx);
}// Make a payment to `toAccount` from `fromAccount` for `amount`.
func makePayment(toAccount horizon.Account, fromAccount horizon.Account, fromKey *keypair.Full, amount string) {
tx, err := buildTx(fromAccount, fromKey, []txnbuild.Operation{
&txnbuild.Payment{
Destination: toAccount.AccountID,
Asset: AstroToken,
Amount: amount,
},
})
check(err)
resp, err := client.SubmitTransaction(tx)
check(err)
}
// Perform a clawback by `byAccount` of `amount` from `fromAccount`.
func doClawback(byAccount horizon.Account, byKey *keypair.Full, fromAccount horizon.Account, amount string) {
tx, err := buildTx(byAccount, byKey, []txnbuild.Operation{
&txnbuild.Clawback{
From: fromAccount.AccountID,
Asset: AstroToken,
Amount: amount,
},
})
check(err)
resp, err := client.SubmitTransaction(tx)
check(err)
}These snippets will help us with the final composition: making some payments to distribute the asset to the world and clawing some of it back.
def examplePaymentClawback():
accounts = getAccounts()
accountA, accountB, accountC = accounts
makePayment(accountB, accountA, A, "1000")
makePayment(accountC, accountB, B, "500")
doClawback(accountA, A, accountC, "250")
accounts = getAccounts()
showBalances(accounts)function examplePaymentClawback() {
return getAccounts()
.then(function (accounts) {
let [accountA, accountB, accountC] = accounts;
return makePayment(accountB, accountA, A, "1000")
.then(makePayment(accountC, accountB, B, "500"))
.then(doClawback(accountA, A, accountC, "250"));
})
.then(getAccounts)
.then(showBalances);
}
preamble().then(examplePaymentClawback);private static void examplePaymentClawback() throws IOException {
AccountResponse[] accounts = getAccounts();
AccountResponse accountA = accounts[0];
AccountResponse accountB = accounts[1];
AccountResponse accountC = accounts[2];
makePayment(accountB, accountA, A, "1000");
makePayment(accountC, accountB, B, "500");
doClawback(accountA, A, accountC, "250");
accounts = getAccounts();
showBalances(accounts);
}func examplePaymentClawback() {
accounts, err := getAccounts()
check(err)
accountA := accounts[0]
accountB := accounts[1]
accountC := accounts[2]
makePayment(accountB, accountA, A, "1000")
makePayment(accountC, accountB, B, "500")
doClawback(accountA, A, accountC, "250")
accounts, err = getAccounts()
check(err)
showBalances(accounts)
}After running our example, we should see the balances reflect the example flow:
A - GCIHA...72MJN: 0
B - GDS5N...C7KKX: 500
C - GC2BK...CQVGF: 250
Notice that
:::info
It may be strange that AstroToken, but that’s exactly how issuing works: you create value where there used to be none. Sending an asset to its issuing account is equivalent to burning it, and auditing the total amount of an asset in existence is one of the benefits of properly distributing an asset via a distribution account, which we avoid doing here for example brevity.
:::
Direct payments aren’t the only way to transfer assets between accounts: claimable balances also do this. Since they are a separate payment mechanism, they need a separate clawback mechanism. For our example, you should be familiar with resolving balance IDs.
We need some additional helper methods to get started working efficiently with claimable balances:
def createClaimable(fromAccount, fromKey, toAccount, amount):
tx = buildTx(fromAccount, fromKey, [
Operation.create_claimable_balance(
asset = AstroToken,
amount = amount,
claimants = [
Claimant(
destination = toAccount.account_id
)
]
)
])
response = server.submit_transaction(tx)
return response
def getBalanceId(txResponse):
txResult = xdr.TransactionResult.from_xdr(txResponse["result_xdr"], "base64")
operationResult = txResult.result.results[0]
creationResult = operationResult.tr.create_claimable_balance_result
return creationResult.balance_id.to_xdr()
def clawbackClaimable(issuerAccount, issuerKey, balanceId):
tx = buildTx(issuerAccount, issuerKey, [
Operation.clawback_claimable_balance(balance_id = balanceId)
])
return server.submit_transaction(tx)function createClaimable(fromAccount, fromKey, toAccount, amount) {
return server.submitTransaction(
buildTx(fromAccount, fromKey, [
sdk.Operation.createClaimableBalance({
asset: AstroToken,
amount: amount,
claimants: [new sdk.Claimant(toAccount.accountId())],
}),
]),
);
}
function getBalanceId(txResponse) {
const txResult = sdk.xdr.TransactionResult.fromXDR(
txResponse.result_xdr,
"base64",
);
const operationResult = txResult.result().results()[0];
let creationResult = operationResult.value().createClaimableBalanceResult();
return creationResult.balanceId().toXDR("hex");
}
function clawbackClaimable(issuerAccount, issuerKey, balanceId) {
return server.submitTransaction(
buildTx(issuerAccount, issuerKey, [
sdk.Operation.clawbackClaimableBalance({ balanceId }),
]),
);
}public static SubmitTransactionResponse createClaimable(
AccountResponse fromAccount,
KeyPair fromKey,
AccountResponse toAccount,
String amount
) throws IOException {
Transaction tx = buildTx(
fromAccount,
fromKey,
new Operation[]{
CreateClaimableBalanceOperation.Builder(AstroToken, amount)
.addClaimant(
Claimant.create(
toAccount.getAccountId()
)
)
.build()
}
);
return server.submitTransaction(tx);
}
public static String getBalanceId(SubmitTransactionResponse txResponse) {
XdrDataInputStream txResultStream = new XdrDataInputStream(
Base64.getDecoder().decode(txResponse.getResultXdr())
);
TransactionResult txResult = TransactionResult.decode(txResultStream);
OperationResult opResult = txResult.getResult().getResults()[0];
CreateClaimableBalanceResult creationResult = opResult.getTr().getCreateClaimableBalanceResult();
return creationResult.getBalanceId().toXdrBase64();
}
public static SubmitTransactionResponse clawbackClaimable(
AccountResponse issuerAcc,
KeyPair issuerKey,
String balanceId
) throws IOException {
Transaction tx = buildTx(issuerAcc, issuerKey, new Operation[]{
ClawbackClaimableBalanceOperation.Builder(balanceId).build()
});
return server.submitTransaction(tx);
}func createClaimable(
fromAccount horizon.Account,
fromKey *keypair.Full,
toAccount horizon.Account,
amount string
) (*horizon.Transaction, error) {
tx, err := buildTx(fromAccount, fromKey, []txnbuild.Operation{
&txnbuild.CreateClaimableBalance{
Asset: AstroToken,
Amount: amount,
Claimants: []txnbuild.Claimant{
txnbuild.NewClaimant(
toAccount.AccountID
)
},
}
})
check(err)
return client.SubmitTransaction(tx)
}
func getBalanceId(txResponse *horizon.Transaction) (string, error) {
txResultBytes, err := base64.StdEncoding.DecodeString(txResponse.ResultXdr)
check(err)
var txResult xdr.TransactionResult
_, err = xdr.Unmarshal(txResultBytes, &txResult)
check(err)
operationResult := txResult.Result.Results[0]
creationResult := operationResult.Tr.CreateClaimableBalanceResult
return creationResult.BalanceId.ToXDR(), nil
}
func clawbackClaimable(
issuerAcc horizon.Account,
issuerKey *keypair.Full,
balanceId string
) (*horizon.Transaction, error) {
tx, err := buildTx(issuerAcc, issuerKey, []txnbuild.Operation{
&txnbuild.ClawbackClaimableBalance{
BalanceID: balanceId,
}
})
check(err)
return client.SubmitTransaction(tx)
}Now, we can fulfill the flow: makePayment helper from the earlier example.)
def exampleClaimableBalanceClawback():
accounts = getAccounts()
accountA, accountB, accountC = accounts
makePayment(accountB, accountA, A, "1000")
txResp = createClaimable(accountB, B, accountC, "500")
balanceId = getBalanceId(txResp)
clawbackClaimable(accountA, A, balanceId)
accounts = getAccounts()
showBalances(accounts)function exampleClaimableBalanceClawback() {
return getAccounts()
.then(function (accounts) {
let [accountA, accountB, accountC] = accounts;
return makePayment(accountB, accountA, A, "1000")
.then(() => createClaimable(accountB, B, accountC, "500"))
.then((txResp) => clawbackClaimable(accountA, A, getBalanceId(txResp)));
})
.then(getAccounts)
.then(showBalances);
}public static void exampleClaimableBalanceClawback() throws IOException {
AccountResponse[] accounts = getAccounts();
AccountResponse accountA = accounts[0];
AccountResponse accountB = accounts[1];
AccountResponse accountC = accounts[2];
makePayment(accountB, accountA, A, "1000");
SubmitTransactionResponse txResp = createClaimable(
accountB,
B,
accountC,
"500"
);
clawbackClaimable(accountA, A, getBalanceId(txResp));
accounts = getAccounts();
showBalances(accounts);
}func exampleClaimableBalanceClawback() {
accounts, err := getAccounts()
check(err)
accountA := accounts[0]
accountB := accounts[1]
accountC := accounts[2]
_, err = makePayment(accountB, accountA, A, "1000")
check(err)
txResp, err := createClaimable(accountB, B, accountC, "500")
check(err)
_, err = clawbackClaimable(accountA, A, getBalanceId(txResp))
check(err)
accounts, err = getAccounts()
check(err)
showBalances(accounts)
}After running preamble().then(examplePaymentClawback), we should see the balances reflect our flow:
A - GCIHA...72MJN: 0
B - GDS5N...C7KKX: 500
C - GC2BK...CQVGF: 0
When you enable the AUTH_CLAWBACK_ENABLED_FLAG on your account, it will make all future trustlines have clawback enabled for any of your issued assets. This may not always be desirable as you may want certain assets to behave as they did before. Though you could work around this by reissuing assets from a “dedicated clawback” account, you can also simply disable clawbacks for certain trustlines by clearing the TRUST_LINE_CLAWBACK_ENABLED_FLAG on a trustline.
In the following example, we’ll have an account
First, let’s prepare the accounts using the helper functions defined in the earlier examples:
def preambleRedux():
accounts = getAccounts()
enableClawback(accounts[0], A)
establishTrustline(accounts[1], B)function preambleRedux() {
return getAccounts().then((accounts) => {
return enableClawback(accounts[0], A).then(() =>
establishTrustline(accounts[1], B),
);
});
}public static void preambleRedux() throws IOException {
AccountResponse[] accounts = getAccounts();
enableClawback(accounts[0], A);
establishTrustline(accounts[1], B);
}func preambleRedux() {
accounts, err := getAccounts()
check(err)
err = enableClawback(accounts[0], A)
check(err)
err = establishTrustline(accounts[1], B)
check(err)
}Now, let’s distribute some of our asset to
def disableClawback(issuerAccount, issuerKeys, forTrustor):
tx = buildTx(issuerAccount, issuerKeys, [
Operation.set_trust_line_flags(
trustor = forTrustor.account_id,
asset = AstroToken,
clear_flags = Operation.Flag.TRUSTLINE_CLAWBACK_ENABLED_FLAG,
)
])
response = server.submit_transaction(tx)
return response
def exampleSelectiveClawback():
accounts = getAccounts()
accountA, accountB = accounts
makePayment(accountB, accountA, A, "1000")
accounts = getAccounts()
showBalances(accounts)
doClawback(accountA, A, accountB, "500")
accounts = getAccounts()
showBalances(accounts)
disableClawback(accountA, A, accountB)
try:
doClawback(accountA, A, accountB, "500")
except Exception as e:
if 'op_not_clawback_enabled' in str(e):
print("Clawback failed, as expected!")
else:
print("Uh-oh, other failure occurred")
accounts = getAccounts()
showBalances(accounts)function disableClawback(issuerAccount, issuerKeys, forTrustor) {
return server.submitTransaction(
buildTx(issuerAccount, issuerKeys, [
sdk.Operation.setTrustLineFlags({
trustor: forTrustor.accountId(),
asset: AstroToken,
flags: {
clawbackEnabled: false,
},
}),
]),
);
}
function exampleSelectiveClawback() {
return getAccounts()
.then((accounts) => {
let [accountA, accountB] = accounts;
return makePayment(accountB, accountA, A, "1000")
.then(getAccounts)
.then(showBalances)
.then(() => doClawback(accountA, A, accountB, "500"))
.then(getAccounts)
.then(showBalances)
.then(() => disableClawback(accountA, A, accountB))
.then(() => doClawback(accountA, A, accountB, "500"))
.catch((err) => {
if (err.response && err.response.data) {
// This is a very specific way to check for errors,
// and you should probably never do it this way.
// We do this to demonstrate that the clawback
// error *does* occur as expected here.
const opErrors = err.response.data.extras.result_codes.operations;
if (
opErrors &&
opErrors.length > 0 &&
opErrors[0] === "op_not_clawback_enabled"
) {
console.log("Clawback failed, as expected!");
} else {
console.log("Uh-oh, other failure occurred");
}
} else {
console.error("Uh-oh, unknown failure");
}
});
})
.then(getAccounts)
.then(showBalances);
}public static SubmitTransactionResponse disableClawback(
AccountResponse issuerAccount,
KeyPair issuerKeys,
AccountResponse forTrusto
) throws IOException {
Transaction transaction = buildTx(issuerAccount, issuerKeys, new Operation[]{
new SetTrustLineFlagsOperation.Builder(
forTrustor.getAccountId(),
AstroToken
)
.setClearFlags(SetTrustLineFlagsOperation.Flag.TRUSTLINE_CLAWBACK_ENABLED_FLAG)
.build()
});
return server.submitTransaction(transaction);
}
public static void exampleSelectiveClawback() throws IOException {
AccountResponse[] accounts = getAccounts();
AccountResponse accountA = accounts[0];
AccountResponse accountB = accounts[1];
makePayment(accountB, accountA, A, "1000");
accounts = getAccounts();
showBalances(accounts);
doClawback(accountA, A, accountB, "500");
accounts = getAccounts();
showBalances(accounts);
disableClawback(accountA, A, accountB);
try {
doClawback(accountA, A, accountB, "500");
} catch (Exception e) {
// This is a very specific way to check for errors,
// and you should probably never do it this way.
// We do this to demonstrate that the clawback
// error *does* occur as expected here.
if (e.getMessage().contains("op_not_clawback_enabled")) {
System.out.println("Clawback failed, as expected!");
} else {
System.out.println("Uh-oh, some other failure");
}
}
accounts = getAccounts();
showBalances(accounts);
}func disableClawback(
issuerAccount horizon.Account,
issuerKey *keypair.Full,
forTrustor horizon.Account
) {
tx, err := buildTx(issuerAccount, issuerKey, []txnbuild.Operation{
&txnbuild.SetTrustLineFlags{
Trustor: forTrustor.AccountID,
Asset: AstroToken,
ClearFlags: []txnbuild.TrustLineFlags{
txnbuild.TrustLineClawbackEnabledFlag
},
},
})
check(err)
_, err = client.SubmitTransaction(tx)
return err
}
func exampleSelectiveClawback() error {
accounts, err := getAccounts()
check(err)
accountA := accounts[0]
accountB := accounts[1]
_, err = makePayment(accountB, accountA, A, "1000")
check(err)
accounts, err = getAccounts()
check(err)
showBalances(accounts)
_, err = doClawback(accountA, A, accountB, "500")
check(err)
accounts, err = getAccounts()
check(err)
showBalances(accounts)
err = disableClawback(accountA, A, accountB)
check(err)
_, err = doClawback(accountA, A, accountB, "500")
if err != nil {
if err.Error() == "op_not_clawback_enabled" {
fmt.Println("Clawback failed, as expected!")
} else {
return fmt.Println("Uh-oh, some other failure occurred")
}
}
accounts, err = getAccounts()
check(err)
showBalances(accounts)
}Run the example (e.g. via preambleRedux().then(exampleSelectiveClawback)) and observe its result:
A - GCIHA...72MJN: 0
B - GDS5N...C7KKX: 1000
A - GCIHA...72MJN: 0
B - GDS5N...C7KKX: 500
Clawback failed, as expected!
A - GCIHA...72MJN: 0
B - GDS5N...C7KKX: 500