-
Notifications
You must be signed in to change notification settings - Fork 134
/
clawbacks.mdx
1166 lines (985 loc) · 36.2 KB
/
clawbacks.mdx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
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](../../../tokens/control-asset-access.mdx#clawback-enabled-0x8) asset. Introduced in [CAP-0035](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md), issuers can clawback from account trustlines or claimable balances. Clawbacks effectively [destroy](https://stellar.org/blog/developers/using-protocol-17s-asset-clawback) 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.
## Operations
### Set Options
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.
### 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.
### Clawback Claimable Balance
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](../transactions-specialized/claimable-balances.mdx#additional-parameters).
### Set Trust Line Flag
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.
## Examples
Here we’ll cover the following approaches to clawing back an asset.
- **[Example 1](#example-1-payments):** 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](#example-2-claimable-balances):** $\mathcal{B}$ creates a claimable balance for $\mathcal{C}$, and $\mathcal{A}$ claws back the new claimable balance.
- **[Example 3](#example-3-selectively-enabling-clawback):** $\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.
### Preamble: Issuing a Clawback-able 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](../../../tokens/control-asset-access.mdx#issuing-and-distribution-accounts) 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.
:::
<CodeExample>
```python
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"
```
```js
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";
}
```
```java
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";
}
}
```
```go
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"
}
```
</CodeExample>
### Example 1: Payments
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 $\mathcal{A}$ will pay Account $\mathcal{B}$ with 1000 `AstroToken`; then, $\mathcal{B}$ will pay Account $\mathcal{C}$ 500 tokens in turn. Finally, $\mathcal{A}$ will claw back half of $\mathcal{C}$’s balance, burning 250 tokens forever. Let’s dive into the helper functions:
<CodeExample>
```python
# 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)
```
```js
// 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,
}),
]),
);
}
```
```java
// 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);
}
```
```go
// 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)
}
```
</CodeExample>
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.
<CodeExample>
```python
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)
```
```js
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);
```
```java
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);
}
```
```go
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)
}
```
</CodeExample>
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 $\mathcal{A}$ (the issuer) holds none of the asset despite clawing back 250 from $\mathcal{C}$. This should drive home the fact that clawed-back assets are burned, not transferred.
:::info
It may be strange that $\mathcal{A}$ never holds any `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.
:::
### Example 2: Claimable Balances
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](https://developers.stellar.org/docs/learn/encyclopedia/transactions-specialized/claimable-balances#example).
We need some additional helper methods to get started working efficiently with claimable balances:
<CodeExample>
```python
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)
```
```js
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 }),
]),
);
}
```
```java
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);
}
```
```go
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)
}
```
</CodeExample>
Now, we can fulfill the flow: $\mathcal{A}$ pays $\mathcal{B}$, who sends a claimable balance to $\mathcal{C}$, who gets it clawed back by $\mathcal{A}$. (Note that we rely on the `makePayment` helper from the earlier example.)
<CodeExample>
```python
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)
```
```js
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);
}
```
```java
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);
}
```
```go
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)
}
```
</CodeExample>
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
```
### Example 3: Selectively Enabling Clawback
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 $\mathcal{A}$ issue a new asset and distribute it to a second account $\mathcal{B}$. Next, we’ll demonstrate how $\mathcal{A}$ claws back some of the assets from $\mathcal{B}$, then clears the trustline and can no longer claw back the asset.
First, let’s prepare the accounts using the helper functions defined in the earlier examples:
<CodeExample>
```python
def preambleRedux():
accounts = getAccounts()
enableClawback(accounts[0], A)
establishTrustline(accounts[1], B)
```
```js
function preambleRedux() {
return getAccounts().then((accounts) => {
return enableClawback(accounts[0], A).then(() =>
establishTrustline(accounts[1], B),
);
});
}
```
```java
public static void preambleRedux() throws IOException {
AccountResponse[] accounts = getAccounts();
enableClawback(accounts[0], A);
establishTrustline(accounts[1], B);
}
```
```go
func preambleRedux() {
accounts, err := getAccounts()
check(err)
err = enableClawback(accounts[0], A)
check(err)
err = establishTrustline(accounts[1], B)
check(err)
}
```
</CodeExample>
Now, let’s distribute some of our asset to $\mathcal{B}$, just to claw it back. Then, we’ll clear the flag from the trustline and show that another clawback isn’t possible:
<CodeExample>
```python
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)
```
```js
function disableClawback(issuerAccount, issuerKeys, forTrustor) {
return server.submitTransaction(
buildTx(issuerAccount, issuerKeys, [
sdk.Operation.setTrustLineFlags({
trustor: forTrustor.accountId(),
asset: AstroToken,
flags: {