Skip to content

Commit 4617740

Browse files
JFWooten4John Wooten
andauthored
🀝 Elliot merge branch ← main
* πŸ” Channel accounts: explain resolutions Page 1 of 6 * πŸ” Channel accounts: simplify narrative Page 1 of 6 * πŸ” Channel accounts: specify cards Page 1 of 6 * πŸ” Channel accounts: finalize visuals Page 1 of 6 * πŸ” Channel accounts: simplify narrative Page 1 of 6 * πŸ” Channel accounts: expand details Page 1 of 6 * πŸ” Channel accounts: hyperlinks, context - Starlight active, details confirmed with SDF at https://discord.com/channels/897514728459468821/907476473739354153/1259478260220301362 - Searching for src on global consensus data packet propogation for relevance in random submisison delay - Need to get hard reference for Protocol 20 one-txn-per-ledger limit * πŸ” Channel accounts: initial diagrams * πŸ” Channel accounts: reference configuration - Use 100px corner rounding * πŸ” Channel accounts: KaTeX formatting - First time working with this in mdx, pretty nice * πŸ” Channel accounts: context, links * πŸ” Channel accounts: conceptual images * πŸ” Channel accounts: simplify image * πŸ” Channel accounts: prioritize readability * πŸ” Channel accounts: overload example * πŸ” Channel accounts: configuration example * 🫴🏽 Claimable balances: first example * 🫴🏽 Claimable balances: second example Status diction in determinant per stellar/stellar-protocol#1504 * 🫴🏽 Claimable balances: third example * 🫴🏽 Claimable balances: expand precomputation * πŸ”Ž Refresh: asset design considerations See stellar#864 * 🦞 Clawbacks: confer readable diction * 🦞 Clawbacks: minor example diction * 🦞 Clawbacks: format account names * 🦞 Clawbacks: format more names * 🦞 Clawbacks: apply name diction See stellar/stellar-protocol#1516 (comment) * 🦞 Clawbacks: translate preamble example * 🦞 Clawbacks: expand example one * 🦞 Clawbacks: translate next instances * 🦞 Clawbacks: continue example dev * πŸ’± Trading examples: add lumenaut * ⏬ Prep for GH sync * πŸ’± Trading examples: clarify narrative A lot more to explain here given common perspective, available at https://www.youtube.com/live/3AGhdiQeXE0?t=1800 * πŸ’± Trading examples: contextualize sources While I appreciate that the legacy dialogue around atomic swaps has been between chains, I respectfully submit that this is only because there's never before been a global ledger that could accurately account for a variety of assets in any meaningfully-scalable way. Swaps being "automatically cancelled" is a bit of a mathematical abstraction, but I can't think of another way to explain it simply. src: https://bitcointalk.org/index.php?topic=193281.0 * πŸ™Œ Missed a reference link Can I just take a minute to say how mind-boggling it is that MtGox is referenced on the Wikipedia page for OBs? * πŸ’± Trading examples: sell offers * πŸ’± Trading examples: level two per user example * πŸ’± Trading examples: time & sales * πŸ” Clarify channel context links * πŸ” Further advance text flow * πŸ” Start last code examples We're walking through an example implementation for general understanding, but the efficient implementation here likely falls on the applicator. * πŸ” Remove random channel generation I just don't see why we need to explicitly walk through this in a relatively advanced guide. * πŸ” Rest of authorization example Not convinced we need to include txn submission for the third time. * πŸ” Remove adding channel custody * πŸ” Clear up last tasks * πŸ” Start state rotation example The higher fee assumes we want these executed in the same block, so let's bid for that. Also, since this is an advanced guide, I'm taking out the redundant/verbose tx timeouts. * πŸ” Temporary merge, nonfinal publication I've finally hit my breaking point and am upgrading to Ubuntu. Accordingly, I'm synching up my last local changes despite the reality that I've held these back for some time because most of the substance was moved to protocol discussion 1558. But thanks, reccomendation, and shoutout to Silence for dropping in with some stellar wisdom. πŸ€πŸ§™β€β™‚οΈπŸ§  * πŸ”— Minimum compilation link requirements * πŸ–ŒοΈ Prettier compilation demo fixes * πŸ” Clarify base fee, miscellaneous 🀝🏻 * πŸ‘½ Translate java to JS * πŸ” Last example java & go * πŸ” Closing example explanation, diagrams * πŸ” Put back `set timeouts` * πŸ” Cleanup remaining frame items * πŸ” Comment active-tense transitive verbs * πŸ” Finalize the story flow * πŸ” Polish off minor syntax * πŸ”— Remove depricated community link * πŸ”Ž Clarify note on trustlines * 🫴🏽 Finish most cleaning up (still need to clarify on min/base fee syntax for 1044) * πŸ”— Update simplified syntax reference * 🦞 Clean up final examples * πŸ’± Remove items explicitly moved Id. at link 2 * πŸ’± Remove duplicate placeholder drafts * πŸ’± Sidebar section intro description * πŸ’± First rewrite run through See public drafting at https://x.com/JFWooten4/status/1853966327318520003 * πŸ’± Clean up scaffolding leftovers - By the time this pull merges, the volume/trade approx should hit. - Fixed missing API doc structure MethodTable explainer. - Added Lumenauts video to SCP explainer for accessability. * πŸ’± Translate starting AMM preamble * πŸ’± Capital pool > liquidity pool Effectively all protocol 18 coverage references AMMs because AMMs are generally the more common industry term. While I appreciate that exact diction can be alluring (https://github.com/orgs/WhyDRS/discussions/21), might we scope the introductory page at least to explain rather than confuse readers? * πŸ’± Translate two AMM steps For diction in _Id_, _see also_ R282 at JFWooten4/free-markets@dba9447#r149283300 * πŸ“ Follow up on this * πŸ’± Translate removing AMM liquidity And simplify the go newTxBuilder preconditions * πŸ’± Translate Java wrap-up example Gives defereance to full disaply decimals rather than two-digit truncation. As an aside, are there any reputable anchors using display_digitals in their tomls? * πŸ’± Last legacy, 535b09b fix Addresses the logic combination and Go documentation. Since we're using it to build an obj to add ops to, signing should stay as is. * πŸ’± Clean up go conclusion * πŸ“Œ Simplify starting frame, independence * πŸ’± Seperate preliminary config, example I've been digging through the commit history to uncover the origins of some of the JS nesting before stellar#214... I'm updating them to be a little more responsive, readable, and reusable with async waits * πŸ–ŒοΈ Update prettier config note I was messing around with `prettier-plugin-sh` and figured the note could be more localized in case we add tabWidths or such later on here (albeit you can locally inspect the upstream import for equivalent affect) * πŸ’± Optimize, clarify global declarations It could be prudent to globalize the accounts so that we can walk through the other limit order examples * πŸ’± DEX code examples setup No known existing community opinions or best practices on the java syntax per https://discord.com/channels/897514728459468821/966788672164855829/1314630372042084534 in re stellar#1044. I know some of the existing pages have been loosely casted, but there seem to be a lot of new users complaining about Docs examples not compiling or running locally given test data. * πŸ’± Initial sell offer examples * πŸ’± Example resolving limit OB * πŸ’± Pricing point local calculation * πŸ’± Start prepping final flow * πŸ’± Continue on the intro Most of the present code exemplifications are done or should elsewise be refrenced in text and then relied upon for individual pages to have their own examples. * πŸ’± Start of execution chat Some more here dependent on XDR and propogation implementations, which are good for future scopes per https://discord.com/channels/897514728459468821/907476473739354153/1273021348628664433 * πŸ’± Migrate some ancillary points Relatively scope limited per https://github.com/JFWooten4/JFWooten4/blob/main/decisions/core-723-fn.md * πŸ’± Introduce the OB outreach Sort of like how this binds the AttriubteTable to its own scope, especially since it has the same background color. * πŸ’± Translate pricing calculation examples * πŸ› Reinstate space line seperators * πŸ’± Remove elementary explanation diction * πŸ–‹ Some primative punctuation upgrades * ✏ Operations as complete(r) sentences * πŸ“Š Upgrade Dashboard API version * πŸ’± First terminus run through * πŸ’± Second terminus run through * πŸ’± Small example bug TODOs * πŸ› compilation bug fixes, hrefs I understand there's more to do in `docs\data\READ_FIRST.md`, but I'm just not going to deal with that until stellar#1044 * πŸ’± Add pending relevant backlinks * πŸ›yarn fixes, format checks This way only runs the Husky pre-commit if you have yarn installed, which should help with stellar#1044 compatability, given those with write access can quickly (via bot?) run the formatting. i had a lot of problems with this three weeks ago when editing on an offline laptop that didn't have all the dependencies involved. Even though I was going to take care of the nuances on this main desktop here, I couldn't synch up my work to the branch, and thus it was hard to manually override the git commit checks. * 🐜 Reformat the operations page Husky changes here should respect stellar#96 given the autochecks run formatter and fail if not prettier at `check MDX` step * πŸ’± narrative done; last technicals * πŸ€·β€β™‚οΈ a lot of prettier-ness * πŸ’± remove rest of politics * πŸ’± trim down until SD1545 * πŸ’± subsection for offerID resolution Also removes a lot of redundant language from the intent of d5ff964 * 🐞 Active tense on index also bypass the check if yarn run fails for reasons unrelated to file issues like Node version mismatch or corrupt environment * πŸ’± limited pathfiding explanation for example * πŸ’± Minimumm viable path payments This gets into how deeply we want to epxlain paths in stellar#1545 * πŸ’± setup for solo PP workj * πŸ’± simplify start off PP * πŸ’± PP; simplyifing path diction * πŸ’± Simply Liquidity Horizon Documentation This cleans up the wording around stellar#1061 without reviewing the pages we notify users about `consistency`. I think a better long-term solution is a "Consistency" flag added to the affected endpoint pages. This could be a simple button akin to the "Supports Streaming" info box. However, even that seems a verbose solution which would also do well to exist as a simple button (akin to ledgerStorage) > two sentences. * πŸ’± More context for burning prep --------- Co-authored-by: John Wooten <hello@blocktransfer.dev>
1 parent bbbbab7 commit 4617740

13 files changed

Lines changed: 5067 additions & 16 deletions

File tree

β€Ždocs/build/guides/transactions/channel-accounts.mdxβ€Ž

Lines changed: 991 additions & 0 deletions
Large diffs are not rendered by default.

β€Ždocs/build/guides/transactions/claimable-balances.mdxβ€Ž

Lines changed: 588 additions & 0 deletions
Large diffs are not rendered by default.

β€Ždocs/build/guides/transactions/clawbacks.mdxβ€Ž

Lines changed: 1190 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
---
2+
title: Path payments
3+
sidebar_position: 60
4+
description: Send a payment where the asset received differs from the asset sent.
5+
---
6+
7+
path p ayments let [accounts](../../fundamentals/stellar-data-structures/accounts.mdx) send one asset to a recipeint , whoi receiveds a differnt asset. The secure conversion takes advantagfe of the netowrk's [natie liquidity](../sdex/README.mdx) to ewxchange using istant avaliable trades.
8+
9+
The [operations](../../fundamentals/transactions/operations-and-transactions.mdx#operations) specify a minimum amount which the market must meet or excceed. For instance, if you send 10 bananas and rquire a receiver to get at last 15 appleess, then the trahsfer will seek the best exxchange at or above 1.5 each.
10+
11+
TRhis let accoutns transfer value without mandating a single universal currency. You converting one asset ito another at the point of transferring value.
12+
13+
## Routign logic
14+
15+
Pay payments use [the DEX](../sdex/liquidity-on-stellar-sdex-liquidity-pools.mdx#orderbook) or [AMM pools](../sdex/liquidity-on-stellar-sdex-liquidity-pools.mdx#amms) whcih standy readyt t oswap assets at the time of a trnasaction. They cna only consume existing liquidity by drawing on offers previously posted.
16+
17+
Tje tramsfer suicceeds oiF nd only if there's enough eavlaible interest in the [ledger](../../fundamentals/stellar-data-structures/ledgers.mdx) submitted, at the minimum rate. Without this liquiddyty, the cohnversion fails and returns an [errro code](../../../data/apis/horizon/api-reference/errors/README.mdx).
18+
19+
To prepatre for
20+
21+
#### Path Hops
22+
23+
When sending path payments, your transfer can hop between up to six order books or AMMs to find the best price.
24+
25+
Validators perform this arithmatic automatically, allowing you to specify only the lowest total amount you will accept.
26+
27+
At each step in the path, the network calculates the optimal source of liquidity to convert through given your destination asset.
28+
29+
Both the order book and AMMs coexist, providing multiple avenues for liquidity.
30+
31+
Instead of having to choose whether to go through the order book or an AMM, the pathfinding algorithm automatically checks both sources of liquidity and executes new trades using whichever offers the better rate.
32+
33+
It also exchanges with an AMM over an order book at each step if the entire conversation happens at a price equal to or better than limit offers.
34+
35+
## paths {#pathfinding}
36+
37+
[s](../../../data/apis/horizon/api-reference/aggregations/paths/README.mdx) when you call this ou;ll notice differnt `soruce_amoutns` in /data/apis/horizon/api-reference/list-strict-receive-payment-paths or differnt `destination_amount` in docs/data/apis/horizon/api-reference/list-strict-send-payment-paths
38+
39+
### Converting Path Paymtns
40+
41+
offers or AMMs which convert to a minimum specified amount or better.
42+
43+
Transfers automatically use up to six different orderbooks to get the best price, as fully defined in [the Encyclopedia page here] .
44+
45+
Some assets will have a small or nonexistent order book between them. In these cases, Stellar facilitates path payments, which we’ll discuss later.
46+
47+
### Atomicity
48+
49+
payh maymentn operations take adntage of every teerasnaction's exclusive ability to [succeed i n full](../../../fundamentals/transactions/operations-and-transactions) or fail.
50+
51+
This means that your transfer off 10 or more AstroDollars will not
52+
53+
In a path payment, the asset received differs from the asset sent. Rather than the operation transferring assets directly from one account to another, path payments cross through
54+
55+
before arriving at the destination account.
56+
57+
For the path payment to succeed, there has to be enough liquidity path in existence. Conversions can take up to six independent hops to succeed at the best avaliable price.
58+
59+
### Example
60+
61+
Account A sells XLM β†’ [buy XLM / sell ETH β†’ buy ETH / sell BTC β†’ buy BTC / sell USDC] β†’ Account B receives USDC {/* Image suggester here in #944 */}
62+
63+
It is possible for path payments to fail if there are no viable exchange paths.
64+
65+
## Path payments - more info
66+
67+
- Path payments don’t allow intermediate offers to be from the source account as this would yield a worse exchange rate. You’ll need to either split the path payment into two smaller path payments or ensure that the source account’s offers are not at the top of the order book.
68+
- Balances are settled at the very end of the operation.
69+
- This is especially important when (`Destination, Destination Asset) == (Source, Send Asset`) as this provides a functionality equivalent to getting a no-interest loan for the duration of the operation.
70+
- `Destination min` is a protective measure, it allows you to specify a lower bound for an acceptable conversion. If offers in the order books are not favorable enough for the operation to deliver that amount, the operation will fail.
71+
72+
## Operations
73+
74+
Path payments use the Path Payment Strict Send or Path Payment Strict Receive operations.
75+
76+
### Path Payment Strict Send
77+
78+
[errors](../../../data/apis/horizon/api-reference/errors/result-codes/operation-specific/path-payment-strict-send.mdx) Allows a user to specify the amount of the asset to send. The amount received will vary based on offers in the order books and/or liquidity pools.
79+
80+
https://developers.stellar.org/docs/learn/fundamentals/transactions/list-of-operations#path-payment-strict-send
81+
82+
### Path Payment Strict Receive
83+
84+
[errors](../../../data/apis/horizon/api-reference/errors/result-codes/operation-specific/path-payment-strict-receive.mdx) Allows a user to specify the amount of the asset received. The amount sent will vary based on the offers in the order books/liquidity pools.
85+
86+
## Example
87+
88+
First, ensure the receiver has a trustline established for the asset they will receive. In this example, we will use USDC as the asset received. The sender will send XLM, which will be converted to USDC through the path payment operation.
89+
90+
```js
91+
import {
92+
Horizon,
93+
Asset,
94+
Keypair,
95+
TransactionBuilder,
96+
Networks,
97+
BASE_FEE,
98+
Operation,
99+
Memo,
100+
} from "@stellar/stellar-sdk";
101+
102+
const USDC_ISSUER = "GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5"; // USDC issuer on Stellar Testnet
103+
const USDC_ASSET = new Asset("USDC", USDC_ISSUER); // USDC asset on Stellar Testnet
104+
const RECEIVER_SECRET = "S..."; // Receiver's secret key
105+
106+
const SENDER_SECRET = "S..."; // Sender's secret key
107+
const horizonServer = new Horizon.Server("https://horizon-testnet.stellar.org");
108+
109+
// Create a USDC trustline for the receiver
110+
const receiverKP = Keypair.fromSecret(RECEIVER_SECRET);
111+
let account = await horizonServer.loadAccount(receiverKP.publicKey());
112+
let transaction = new TransactionBuilder(account, {
113+
fee: BASE_FEE * 100,
114+
networkPassphrase: Networks.TESTNET,
115+
})
116+
.addOperation(
117+
Operation.changeTrust({
118+
asset: USDC_ASSET,
119+
limit: "10",
120+
}),
121+
)
122+
.addMemo(Memo.text("Trusting USDC"))
123+
.setTimeout(30)
124+
.build();
125+
126+
transaction.sign(receiverKP);
127+
const resp = await SERVER.submitTransaction(transaction);
128+
console.log("resp", resp);
129+
```
130+
131+
Now let's send a path payment from the sender to the receiver, converting XLM to USDC.
132+
133+
```js
134+
// Use path payment to send XLM from the receiver to the sender, who receives USDC
135+
let senderKP = Keypair.fromSecret(SENDER_SECRET);
136+
let account = await horizonServer.loadAccount(senderKP.publicKey());
137+
let transaction = new TransactionBuilder(account, {
138+
fee: BASE_FEE * 100,
139+
networkPassphrase: Networks.TESTNET,
140+
})
141+
.addOperation(
142+
Operation.pathPaymentStrictReceive({
143+
sendAsset: Asset.native(), // Sending XLM
144+
sendMax: "10", // Maximum amount of XLM to send
145+
destAsset: USDC_ASSET, // Receiving USDC
146+
destAmount: "1", // Amount of USDC to receive
147+
destination: receiverKP.publicKey(), // Receiver's public key
148+
}),
149+
)
150+
.addMemo(Memo.text("XLM to USDC"))
151+
.setTimeout(30)
152+
.build();
153+
154+
transaction.sign(senderKP);
155+
const resp = await horizonServer.submitTransaction(transaction);
156+
console.log("resp", resp);
157+
```
158+
159+
https://developers.stellar.org/docs/learn/fundamentals/transactions/list-of-operations#path-payment-strict-receive
160+
161+
also we need to clairfy chanign API v openApia which si from #991 docs/data/apis/horizon/api-reference/structure/response-format.mdx#L170 \_contra- openapi/horizon/components/examples/responses/Offers/GetAllOffers.yml#L28 ++ openapi/horizon/components/examples/responses/Offers/GetAllOffers.yml#L28

β€Ždocs/data/apis/horizon/api-reference/structure/README.mdxβ€Ž

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,20 @@ sidebar_label: Structure
55
description: Horizon is an API for interacting with the Stellar network.
66
---
77

8-
import DocCardList from "@theme/DocCardList";
8+
import { MethodTable } from "@site/src/components/MethodTable";
99

1010
How Horizon is structured.
1111

12-
<DocCardList />
12+
<MethodTable title="Structure Types">
13+
14+
| | |
15+
| ------------------------------------------------- | --- |
16+
| [Response Format](./response-format.mdx) | |
17+
| [Page Arguments](./pagination/page-arguments.mdx) | |
18+
| [Streaming](./streaming.mdx) | |
19+
| [Rate Limiting](./rate-limiting.mdx) | |
20+
| [XDR](./xdr.mdx) | |
21+
| [Consistency](./consistency.mdx) | |
22+
| [Pagination](./pagination/README.mdx) | |
23+
24+
</MethodTable>

β€Ždocs/data/apis/rpc/api-reference/methods/getLedgerEntries.mdxβ€Ž

Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,202 @@ switch (AMM.switch().value) {
335335
336336
</CodeExample>
337337
338+
### Offers
339+
340+
An offer represents a live order on the DEX. Each offer is identified by its `offerID`. To construct a `LedgerKey` for an offer, you only need the offer ID:
341+
342+
<CodeExample>
343+
344+
```typescript
345+
const offerLedgerKey = xdr.LedgerKey.ledgerKeyOffer(
346+
new xdr.LedgerKeyOffer({
347+
offerID: 123456789n,
348+
}),
349+
);
350+
console.log(offerLedgerKey.toXDR("base64"));
351+
```
352+
353+
</CodeExample>
354+
355+
Once you have the ledger entry, you can extract its fields:
356+
357+
<CodeExample>
358+
359+
```typescript
360+
const offerEntryData = (
361+
await s.getLedgerEntries(offerLedgerKey)
362+
).entries[0].offer();
363+
364+
console.log(`Offer ID: ${offerEntryData.offerId().toString()}`);
365+
console.log(`Seller: ${offerEntryData.sellerId().accountId()}`);
366+
console.log(`Amount: ${offerEntryData.amount().toString()}`); // of selling
367+
console.log(
368+
`Price: ${offerEntryData.price().n().toString()} / ${offerEntryData.price().d().toString()}`,
369+
);
370+
```
371+
372+
</CodeExample>
373+
374+
You can then decode the selling and buying assets the same way you do for Trustlines, by inspecting `offerEntryData.selling()` and `offerEntryData.buying()` using the standard `xdr.Asset` parsing logic.
375+
376+
### Claimable Balances
377+
378+
A claimable balance represents assets that have been locked under certain claim conditions. Each claimable balance is identified by its `balanceId`, which is a 32-byte hash.
379+
380+
To construct a `LedgerKey` for a claimable balance, you need the `balanceId` as a `Buffer` or `Uint8Array`:
381+
382+
<CodeExample>
383+
384+
```typescript
385+
const balanceIdHex =
386+
"407a334017a508fb2bf41952c74f977b46147ed70b175717f8bacc0ca3f2cc5b";
387+
const balanceIdBytes = Buffer.from(balanceIdHex, "hex");
388+
389+
const claimableBalanceLedgerKey = xdr.LedgerKey.ledgerKeyClaimableBalance(
390+
new xdr.LedgerKeyClaimableBalance({
391+
balanceID: xdr.ClaimableBalanceID.claimableBalanceIdTypeV0(balanceIdBytes),
392+
}),
393+
);
394+
console.log(claimableBalanceLedgerKey.toXDR("base64"));
395+
```
396+
397+
</CodeExample>
398+
399+
Once you have the ledger entry, you can extract its fields:
400+
401+
<CodeExample>
402+
403+
```typescript
404+
const claimableBalanceEntryData = (
405+
await s.getLedgerEntries(claimableBalanceLedgerKey)
406+
).entries[0].claimableBalance();
407+
408+
console.log(`Amount: ${claimableBalanceEntryData.amount().toString()} stroops`);
409+
410+
const asset = claimableBalanceEntryData.asset();
411+
// Decode asset similar to as in trustlines
412+
413+
const claimants = claimableBalanceEntryData.claimants();
414+
415+
if (claimableBalanceEntryData.ext().switch().value === 1) {
416+
const flags = claimableBalanceEntryData.ext().v1().flags();
417+
const clawbackEnabled =
418+
(flags &
419+
xdr.ClaimableBalanceFlags.claimableBalanceClawbackEnabledFlag()) !==
420+
0;
421+
console.log(`Clawback Enabled: ${clawbackEnabled}`);
422+
}
423+
```
424+
425+
</CodeExample>
426+
427+
#### Claimants and Predicates
428+
429+
Claimable balances contain one or more claimants, each with a claim predicate. You can iterate through them as follows:
430+
431+
<CodeExample>
432+
433+
```typescript
434+
for (let i = 0; i < claimants.length; i++) {
435+
const claimant = claimants[i].v0();
436+
const destination = claimant.destination().accountId();
437+
console.log(`Claimant ${i + 1}: ${destination}`);
438+
439+
const predicate = claimant.predicate();
440+
const predicateType = predicate.switch().value;
441+
442+
switch (predicateType) {
443+
case xdr.ClaimPredicateType.claimPredicateUnconditional().value:
444+
console.log("Predicate: Unconditional");
445+
break;
446+
case xdr.ClaimPredicateType.claimPredicateBeforeAbsoluteTime().value:
447+
console.log(`Predicate: Before Absolute Time = ${predicate.absBefore().toString()}`);
448+
break;
449+
case xdr.ClaimPredicateType.claimPredicateBeforeRelativeTime().value:
450+
console.log(`Predicate: Before Relative Time = ${predicate.relBefore().toString()} seconds`);
451+
break;
452+
default:
453+
console.log("Predicate: Complex predicate type (AND/OR/NOT)");
454+
break;
455+
}
456+
```
457+
458+
</CodeExample>
459+
460+
#### Flags
461+
462+
If the claimable balance has flags set (not `v0`), you can read them like this:
463+
464+
<CodeExample>
465+
466+
```typescript
467+
switch (claimableBalanceEntryData.ext().switch().value) {
468+
case 0: // No flags
469+
break;
470+
case 1:
471+
const flags = claimableBalanceEntryData.ext().v1().flags();
472+
const clawbackEnabled = (flags & 1) !== 0; // claw = 0x1
473+
console.log(`Clawback Enabled: ${clawbackEnabled}`);
474+
break;
475+
}
476+
```
477+
478+
</CodeExample>
479+
480+
### Liquidity Pools
481+
482+
A liquidity pool represents an Automated Market Maker holding two assets. Each liquidity pool is identified by its `liquidityPoolID`, which is a 32-byte hash.
483+
484+
To construct a `LedgerKey` for an AMM, you need the liquidity-pool ID as a `Buffer` or `Uint8Array`. Core deterministicly stores this as a 64-char hex string.
485+
486+
<CodeExample>
487+
488+
```typescript
489+
const liquidityPoolIdHex =
490+
"82f857462d5304e1ad7d5308fb6d90ff3e70ad8fb07b81d04b12d2cc867fc735";
491+
const liquidityPoolIdBytes = Buffer.from(liquidityPoolIdHex, "hex");
492+
493+
const liquidityPoolLedgerKey = xdr.LedgerKey.ledgerKeyLiquidityPool(
494+
new xdr.LedgerKeyLiquidityPool({
495+
liquidityPoolID: liquidityPoolIdBytes,
496+
}),
497+
);
498+
console.log(liquidityPoolLedgerKey.toXDR("base64"));
499+
```
500+
501+
</CodeExample>
502+
503+
Once you have the ledger entry, you can extract its fields:
504+
505+
<CodeExample>
506+
507+
```typescript
508+
const liquidityPoolEntryData = (
509+
await s.getLedgerEntries(liquidityPoolLedgerKey)
510+
).entries[0].liquidityPool();
511+
512+
console.log(
513+
`Total Pool Shares: ${liquidityPoolEntryData.totalPoolShares().toString()}`,
514+
);
515+
console.log(
516+
`Total Trustlines: ${liquidityPoolEntryData.poolSharesTrustLineCount().toString()}`,
517+
);
518+
519+
const AMM = liquidityPoolEntryData.body();
520+
switch (AMM.switch().value) {
521+
case xdr.LiquidityPoolType.liquidityPoolConstantProduct().value: {
522+
const params = AMM.constantProduct().params();
523+
const fee = params.fee(); // basis points
524+
const assetA = params.assetA();
525+
const assetB = params.assetB();
526+
console.log(`Constant-Product Between: ${assetA} and ${assetB}`);
527+
break;
528+
}
529+
}
530+
```
531+
532+
</CodeExample>
533+
338534
### Contract Data
339535
340536
Suppose we've deployed the [`increment` example contract] and want to find out what value is stored in the `COUNTER` ledger key. To build the key:

0 commit comments

Comments
Β (0)