* Update look up escrows to remove redundant info about lookups via sender/destination. Modify cancel expired escrow for brevity. * Cancel escrow: fix notes * Add draft of updated cancel-escrow.js. * Update intro to escrows. * Add Escrow Tutorial * Minor corrections * Fix headings, add HTML * Update escrow docs This commit re-createsf205a92db2with some adjustments: - Omit the accidentally-created dir full of junk - Fix some typos and one mistake in the Escrow limitations section - Add a table to the EscrowCreate ref to clarify valid combos of fields. * Concept info from send-a-time-held-escrow added to escrow.md * IA: Move "Consensus Network" files This re-creates some work from the original commit56fffe0b9f* Rewrite escrows article (re-created) This commit re-creates relevant work from the following commits:9a4a588f2bUpdate escrow.md context infoe1b017dc83Remove references to using escrow for interledger payments. * IA: Move "XRPL servers" files This re-creates some work from original commit7611979abf* IA: move "production readiness" files. Re-creates work from the following commit:692438693aMove tutorials to concepts * New intro articles Original commit:56fffe0b9f* IA: Reorg account concepts Re-creates some work from original commit56fffe0b9f* IA: reorg transaction concepts Original commits:9d4eff9940WIP - reorg accounts7611979abfWIP dir. reorg * IA: reorg consensus concepts Original commit:56fffe0b9f* IA: Reorg ledger docs Original commit:56fffe0b9f- Rephrased some details of the section * IA: rename issuing/operational addresses page Original commit:56fffe0b9f* Moving use cases * Fleshing out Use Cases Note, the dactyl-config.yml file has not been fully updated. * Clean up checks conceptual info. * Remove redundant checks use case section Original commit:3c29e9c05e* IA: move Dex under tokens Original commit:d08b3ba7d7* Touch up stablecoin issuer use case (#1856) * Consolidate stablecoin use case * Stablecoin issuer: cleanup progress through sending * Stablecoin issuer: reorg second half (Note: the dactyl-config.yml is not fully reconciled yet) * Move rippled and clio tutorials into infrastructure * Remove link to checks amendement. * Add note to account_objects.md about commandline interface type field. * Merge expiration case with lifecycle section. * Interoperability Use Cases * Add graphics to intro * Move escrow use cases to dedicated page. * Update use case page intros and corresponding concept info. * Clarify meaning of direct XRP payments. * Intro link updates * Payment use cases * Remove some unnecessary links in transactions section Original commit:e6fcf4a4dc* Link cleanup in Tokens section Original commit:9588dd5e70* Touch up 'Configure Peering' section Original commit:fc8f0990b8* Clean up links in accounts section Original commit:3da5fde7a8* Add NFT mkt use case * p2p payments: edits to Wallets * Clean up payments use cases * Refine history description * IA: use case cleanup * IA: reconcile servers, ledgers sections * IA: reconcile payment types, tx, tokens * IA: reconcile accounts section * IA: reconcile infra * IA: Fix most broken links * Full Docs Index: omit from sidebar * IA: fix up most broken links * fix Absolute path link to internal content * Quick updates to Software Ecosystem * Remove some absolute links to internal resources * Fix remaining broken links in JA target * Contributing: tweak formatting * Tutorials: fix some minor issues * remove interop use cases * remove intro image and personal references to dennis * alphabetize-transaction-nav * Remove unused files * Add QS escrow tutorials * IA: move ledgers, consensus protocol files around * IA: update nav for new page hierarchy * reordering of topics under new networks and servers top-nav * Move "Naming" to "What is XRP?" * Update dactyl-config.yml Remove xrp.md from the TOC. * Update list-xrp-as-an-exchange.md Update link to what-is-xrp * Update list-xrp-as-an-exchange.ja.md Change link to what-is-xrp * Update currency-formats.md Change link to what-is-xrp * Update currency-formats.ja.md Change link to what-is-xrp * Update cancel-an-expired-escrow.md Change link to what-is-xrp * Update paymentchannelfund.md Change link to what-is-xml * Update look-up-escrows.md Change link to what-is-xrp * Update tokens.md change link to what-is-xrp * Update use-payment-channels.md * Update send-a-time-held-escrow.md Update link to what-is-xml * fix broken links * Update parallel-networks.md Change link to what-is-xml * Update parallel-networks.ja.md * Update invariant-checking.md Remove link to xrp.html * Update invariant-checking.ja.md Remove link to xrp.html * Update transaction-cost.md Change link to what-is-xrp * Update transaction-cost.ja.md Change link to what-is-xrp * Update send-a-conditionally-held-escrow.md Change link to what-is-xrp * Update stablecoin-issuer.md Change link to what-is-xrp * Update tokens.ja.md Change link to what-is-xml * Update autobridging.ja.md Change link to what-is-xrp * Update currency-formats.md update text * reorganize infrastructure nav section * Update currency-formats.md Try removing link altogether. * Update currency-formats.ja.md Remove link to what-is-xrp.html * move commandline usage topic to infrastructure * initial intro rewrite * minor update to language * IA.v3: rm Production Readiness * Delete xrp.md * Update xrp link in snippet * Add redirect for old xrp.html URL * Small edits to 'What is XRP?' article * Add missing imgs * XRP - copy edit per @DennisDawson * restructure tutorials nav and pages * fix broken links * more broken link fixes * Algo trading: 1st draft * Algo trading: notes on taxes * Algo trading: edits per review * algo trading: fix broken link * Ledger structure: rewrite for accuracy and clarity * Update links to removed 'tree format' header * Ledger Structure: Update diagrams * Re-gen CSS for ledger structure changes * Ledger structure: edits per review * IA.v3: fix broken NFT links introduced by rebase * Desktop Wallet (py): update little stuff * Update some capacity/storage details * contribute doc nav update * fix image link in create diagram page * IAv3: Fix 'Ledgers' blurb * Update full history requirements with details from community members * add reviewer suggestions * Edits per @trippled review * Apply suggestions from peer review Co-authored-by: oeggert <117319296+oeggert@users.noreply.github.com> * FH: reword file size limit note per review * Update software ecosystem * updates per review * Minor tweaks to graphics * fixTypos * Update content/concepts/introduction/software-ecosystem.md Co-authored-by: Amarantha Kulkarni <amarantha-k@users.noreply.github.com> * Update content/concepts/introduction/software-ecosystem.md Co-authored-by: Amarantha Kulkarni <amarantha-k@users.noreply.github.com> * [JA] update AccountDelete cost * custom transactors doc * add doc to dactyl config * [JA] fix NonFungibleTokensV1_1 amendment status * [JA] update NFTokenOffer page * Remove old, unused XRP article (#2039) * add reviewer suggestions * Add tooling to check for file/nav consistency - From the repo top, run tool/check_file_consistency.py to look for Markdown files that exist in the "content/" directory but aren't used in the documentation. - New "enforce_filenames" filter prints a warning to console when building, if a file's path and filename don't match expectations based on its place in the nav and top heading. * File consistency checker: correctly handle filenames starting in _ * Remove unused old 'get started' and associated code * Create Resources section & reorg some files - Rename some files/folders based on their place in the nav - Move a bunch of non-documentation stuff, and docs on contributing code and/or docs to the new "Resources" section. - Known issue: nav spills into a second row on page widths between 993px-1110px. To be fixed in a later CSS update, maybe along with making the Resources dropdown multi-column. * Fix #2078 code tab bug CSS not built yet, to reduce merge conflicts. Won't have any effect until that happens. * fix Transaction JSON * [JA] translate contributing contents * fix contributing-to-documentation parent * fix contribute-code blurb * Top nav: add cols for Resources, fix broken links * CSS: fix top nav overflows * Fix broken link from redirect not in JA target * Top nav: add Infra to article types * Update contrib info & rename intro file * [ja] Update link to suggested first page to translate * [ja] fix contribute docs organization * Run private network with docker tutorial (#2065) * [NO-ISSUE] Run private network with docker tutorial Adds a tutorial page in the Infrastructure section on how to run a private XRPL network with Docker. Please let me know if you think this is a useful page to include for developers, whether the steps are clear or not, and if you have suggestions on what can be added to it. * Add minor link fixes and Japanese target * Apply suggestions from code review Co-authored-by: Amarantha Kulkarni <amarantha-k@users.noreply.github.com> * Add link to ripple-docker-testnet setup scripts in See Also section * Update repo URL --------- Co-authored-by: Amarantha Kulkarni <amarantha-k@users.noreply.github.com> * add intro gfx (#2036) * add intro gfx * Move graphic up * Update some graphics with their revised versions * Add updated version of the custodial vs non-custodial graphic --------- Co-authored-by: Amarantha Kulkarni <amarantha-k@users.noreply.github.com> Co-authored-by: Amarantha Kulkarni <akulkarni@ripple.com> * Update to reflect current UNL publishers * [ja] update contributing Co-authored-by: tequ <git@tequ.dev> * Incorporate feedback on "What is XRP" page. (#2099) * Add trademark info for XRP * Revert section to previous state * Fix broken link (#2101) --------- Co-authored-by: Oliver Eggert <oeggert@ripple.com> Co-authored-by: ddawson <dennis.s.dawson@gmail.com> Co-authored-by: Maria Shodunke <mshodunke@ripple.com> Co-authored-by: tequ <git@tequ.dev> Co-authored-by: oeggert <117319296+oeggert@users.noreply.github.com> Co-authored-by: Amarantha Kulkarni <amarantha-k@users.noreply.github.com> Co-authored-by: develoQ <develoQ.jp@gmail.com> Co-authored-by: Maria Shodunke <maria-robobug@users.noreply.github.com> Co-authored-by: Amarantha Kulkarni <akulkarni@ripple.com>
30 KiB
html, parent, blurb, filters, labels
| html | parent | blurb | filters | labels | ||
|---|---|---|---|---|---|---|
| monitor-incoming-payments-with-websocket.html | http-websocket-apis-tutorials.html | WebSocket APIを使用して、新しいXRPペイメントなどを積極的に監視します。 |
|
|
WebSocketを使用した着信ペイメントの監視
このチュートリアルでは、WebSocket rippled APIを使用して、着信ペイメントを監視する方法を説明します。すべてのXRP Ledgerトランザクションは公開されているため、誰もが任意のアドレスへの着信ペイメントを監視できます。
WebSocketは、クライアントとサーバーが1つの接続を確立し、その接続を経由して両方向にメッセージを送信するモデルに従います。この接続は、明示的に閉じる(または接続に障害が発生する)まで続きます。これは、要求ごとにクライアントが新しい接続を開いて閉じるHTTPベースのAPIモデル(JSON-RPCやRESTful APIなど)とは対照的です¹。
ヒント: このページの例はJavaScriptを使用しているため、Webブラウザーでネイティブに実行できます。JavaScriptで開発している場合は、JavaScript向けxrpl.jsライブラリも利用すると、一部の作業を簡素化できます。このチュートリアルでは、xrpl.jsを使用できないその他のプログラミング言語にステップを適合できるよう、xrpl.jsを使用 しない でトランザクションを監視する方法を説明します。
前提条件
- このページの例では、すべての主要な最新ブラウザーで使用できるJavaScriptおよびWebSocketプロトコルを使用しています。JavaScriptにある程度習熟し、WebSocketクライアントを使用する他のプログラミング言語の専門知識があれば、選択する言語に手順を適合させながら進めていくことができます。
- 安定したインターネット接続と
rippledサーバーへアクセスが必要です。埋め込まれている例では、Rippleの公開サーバーのプールに接続します。独自のrippledサーバーを運用する場合は、ローカルでそのサーバーに接続することもできます。 - 丸め方によるエラーを発生させることなくXRPの価値を適切に処理するには、64ビット符号なし整数で計算できる数値タイプを使用できる必要があります。このチュートリアルの例では、big.jsを使用しています。発行済み通貨を使用する場合は、さらに高い精度が求められます。詳細は、通貨の精度を参照してください。
{% set n = cycler(* range(1,99)) %}
{{n.next()}}. XRP Ledgerへの接続
着信ペイメントを監視する最初のステップとして、XRP Ledger、つまりrippledサーバーに接続します。
以下のJavaScriptコードでは、Rippleの公開サーバーのクラスターの1つに接続します。その後、コンソールにメッセージを記録し、[pingメソッド][]を使用して要求を送信します。次に、サーバー側からのメッセージを受信するときに、ハンドラーを設定してコンソールに再度メッセージを記録します。
const socket = new WebSocket('wss://s.altnet.rippletest.net:51233')
socket.addEventListener('open', (event) => {
// This callback runs when the connection is open
console.log("Connected!")
const command = {
"id": "on_open_ping_1",
"command": "ping"
}
socket.send(JSON.stringify(command))
})
socket.addEventListener('message', (event) => {
console.log('Got message from server:', event.data)
})
socket.addEventListener('close', (event) => {
// Use this event to detect when you have become disconnected
// and respond appropriately.
console.log('Disconnected...')
})
上記の例では、Test Net上にあるRippleの公開APIサーバーの1つに対して、安全な接続(wss://)を開きます。代わりにデフォルトの構成を使用してローカルで運用しているrippledサーバーに接続するには、最初の行に以下を使用して、ローカルのポート6006で 安全ではない 接続(ws://)を開きます。
const socket = new WebSocket('ws://localhost:6006')
ヒント: デフォルトでは、ローカルrippledサーバーに接続することで、インターネット上の公開サーバーに接続する際に使用できるパブリックメソッド以外に、すべての管理メソッドと、[server_info][server_infoメソッド]などの一部の応答に含まれる管理者専用データを利用できます。
例:
{{ start_step("Connect") }} Connect Connection status: Not connected
Console:
{{n.next()}}. ハンドラーへの着信メッセージのディスパッチ
WebSocket接続では、複数のメッセージをどちらの方向にも送信することが可能で、要求と応答の間に厳密な1:1の相互関係がないため、各着信メッセージに対応する処理を識別する必要があります。この処理をコーディングする際の優れたモデルとして、「ディスパッチャー」関数の設定が挙げられます。この関数は着信メッセージを読み取り、各メッセージを正しいコードのパスに中継して処理します。メッセージを適切にディスパッチできるように、rippledサーバーでは、すべてのWebSocketメッセージでtypeフィールドを使用できます。
-
クライアント側からの要求への直接の応答となるメッセージの場合、
typeは文字列のresponseです。この場合、サーバーは以下も提供します。-
この応答に対する要求で指定された
idに一致するidフィールド(応答が順序どおりに到着しない可能性があるため、これは重要です)。 -
APIが要求の処理に成功したかどうかを示す
statusフィールド。文字列値successは、成功した応答を示します。文字列値errorは、エラーを示します。警告: トランザクションを送信する際、WebSocketメッセージの先頭にある
successのstatusは、必ずしもトランザクション自体が成功したことを意味しません。これは、サーバーによって要求が理解されたということのみを示します。トランザクションの実際の結果を確認するには、トランザクションの結果の確認を参照してください。
-
-
サブスクリプションからのフォローアップメッセージの場合、
typeは、新しいトランザクション、レジャーまたは検証の通知など、フォローアップメッセージのタイプを示します。または継続しているpathfinding要求のフォローアップを示します。クライアントがこれらのメッセージを受信するのは、それらをサブスクライブしている場合のみです。
ヒント: JavaScript向けxrpl.jsは、デフォルトでこのステップに対応しています。すべての非同期API要求はPromiseを使用して応答を提供します。また.on(event, callback)メソッドを使用して、ストリームをリッスンできます。
以下のJavaScriptコードでは、API要求を便利な非同期Promiseに変換するヘルパー関数を定義し、他のタイプのメッセージをグローバルハンドラーにマップするインターフェイスを設定します。
const AWAITING = {}
const handleResponse = function(data) {
if (!data.hasOwnProperty("id")) {
console.error("Got response event without ID:", data)
return
}
if (AWAITING.hasOwnProperty(data.id)) {
AWAITING[data.id].resolve(data)
} else {
console.error("Response to un-awaited request w/ ID " + data.id)
}
}
let autoid_n = 0
function api_request(options) {
if (!options.hasOwnProperty("id")) {
options.id = "autoid_" + (autoid_n++)
}
let resolveHolder;
AWAITING[options.id] = new Promise((resolve, reject) => {
// Save the resolve func to be called by the handleResponse function later
resolveHolder = resolve
try {
// Use the socket opened in the previous example...
socket.send(JSON.stringify(options))
} catch(error) {
reject(error)
}
})
AWAITING[options.id].resolve = resolveHolder;
return AWAITING[options.id]
}
const WS_HANDLERS = {
"response": handleResponse
// Fill this out with your handlers in the following format:
// "type": function(event) { /* handle event of this type */ }
}
socket.addEventListener('message', (event) => {
const parsed_data = JSON.parse(event.data)
if (WS_HANDLERS.hasOwnProperty(parsed_data.type)) {
// Call the mapped handler
WS_HANDLERS[parsed_data.type](parsed_data)
} else {
console.log("Unhandled message from server", event)
}
})
// Demonstrate api_request functionality
async function pingpong() {
console.log("Ping...")
const response = await api_request({command: "ping"})
console.log("Pong!", response)
}
pingpong()
{{ start_step("Dispatch Messages") }} Enable Dispatcher Ping!
Responses
{{n.next()}}. アカウントのサブスクライブ
トランザクションがアカウントに影響を及ぼすたびに即座に通知を取得するには、[subscribeメソッド][]を使用してアカウントをサブスクライブします。実際には、このアカウントはあなた自身のアカウントでなくてもかまいません。すべてのトランザクションは公開されているため、任意のアカウントで、または複数のアカウントでもサブスクライブできます。
1つ以上のアカウントをサブスクライブした場合、指定したアカウントのいずれかに何らかの影響を及ぼす各検証済みトランザクションについて、"type": "transaction"が含まれるメッセージがサーバーから送信されます。これを確認するには、トランザクションメッセージで"validated": trueを探します。
以下のコードサンプルは、Test Net Faucetの送信側アドレスをサブスクライブします。このコードサンプルでは、前のステップのディスパッチャーにハンドラーを追加することで、該当する各トランザクションのメッセージを記録します。
async function do_subscribe() {
const sub_response = await api_request({
command:"subscribe",
accounts: ["rUCzEr6jrEyMpjhs4wSdQdz4g8Y382NxfM"]
})
if (sub_response.status === "success") {
console.log("Successfully subscribed!")
} else {
console.error("Error subscribing: ", sub_response)
}
}
do_subscribe()
const log_tx = function(tx) {
console.log(tx.transaction.TransactionType + " transaction sent by " +
tx.transaction.Account +
"\n Result: " + tx.meta.TransactionResult +
" in ledger " + tx.ledger_index +
"\n Validated? " + tx.validated)
}
WS_HANDLERS["transaction"] = log_tx
以下の例では、別のウィンドウまたは別のデバイスでTransaction Senderを開くことと、サブスクライブしているアドレスへのトランザクションの送信を試みます。
{{ start_step("Subscribe") }} Subscribe
Transactions
Result: " + tx.meta.TransactionResult + " in ledger " + tx.ledger_index + "
Validated? " + tx.validated) } WS_HANDLERS["transaction"] = log_tx </script>
{{n.next()}}. 着信ペイメントの読み取り
アカウントをサブスクライブすると、 アカウントへのすべてのトランザクションとアカウントからのすべてのトランザクション 、および アカウントに間接的に影響を及ぼすトランザクション に関するメッセージが表示されます。この例として、発行済み通貨の取引があります。アカウントが着信ペイメントを受け取った日時を認識することを目的とする場合、トランザクションストリームを絞り込んで、実際に支払われた額に基づいて支払いを処理する必要があります。以下の情報を探します。
-
validatedフィールドは、トランザクションの結果が最終的であることを示します。これは、accountsをサブスクライブする場合に常に当てはまりますが、accounts_proposedまたはtransactions_proposedストリーム も サブスクライブしている場合は、サーバーは未確認のトランザクションに関して同様のメッセージを同じ接続で送信します。予防策として、validatedフィールドを常に確認することをお勧めします。 -
meta.TransactionResultフィールドは、トランザクションの結果です。結果がtesSUCCESSでない場合は、トランザクションは失敗したため、値を送信できません。 -
transaction.Accountフィールドはトランザクションの送信元です。他の人が送信したトランザクションのみを探している場合は、このフィールドがあなたのアドレスと一致するトランザクションを無視できます(自身に対する複数通貨間の支払いが 可能である 点に注意してください)。 -
transaction.TransactionTypeフィールドはトランザクションのタイプです。アカウントに通貨を送金できる可能性があるトランザクションのタイプは以下のとおりです。-
[Paymentトランザクション][] はXRPまたは発行済み通貨を送金できます。受取人のアドレスを含んでいる
transaction.Destinationフィールドによってこれらを絞り込み、必ずmeta.delivered_amountを使用して実際に支払われた額を確認します。XRPの額は、文字列のフォーマットで記述されます。警告: 代わりに
transaction.Amountフィールドを使用すると、Partial Paymentの悪用に対して脆弱になる可能性があります。不正使用者はこの悪用を行ってあなたをだまし、あなたが支払ったよりも多くの金額を交換または引き出すことができます。 -
**[CheckCashトランザクション][]**では、アカウントは別のアカウントの[CheckCreateトランザクション][]によって承認された金額を受け取ることができます。CheckCashトランザクションのメタデータを確認すると、アカウントが受け取った通貨の額を確認できます。
-
[EscrowFinishトランザクション][] は、以前の[EscrowCreateトランザクション][]によって作成されたEscrowを終了することでXRPを送金できます。EscrowFinishトランザクションのメタデータを確認すると、escrowからXRPを受け取ったアカウントと、その額を確認できます。
-
[OfferCreateトランザクション][] はアカウントがXRP Ledgerの分散型取引所で以前発行したオファーを消費することで、XRPまたは発行済み通貨を送金できます。オファーを発行しないと、この方法で金額を受け取ることはできません。メタデータを確認して、アカウントが受け取った通貨(この情報がある場合)と、金額を確認します。
-
[PaymentChannelClaimトランザクション][] では、Payment ChannelからXRPを送金できます。メタデータを確認して、トランザクションからXRPを受け取ったアカウント(この情報がある場合)を確認します。
-
[PaymentChannelFundトランザクション][] は、閉鎖された(期限切れの)Payment Channelから送金元にXRPを返金することができます。
-
-
metaフィールドには、1つまたは複数の通貨の種類とその正確な金額、その送金先などを示すトランザクションメタデータが示されています。トランザクションメタデータを理解する方法の詳細は、トランザクションの結果の確認を参照してください。
以下のサンプルコードは、上に示したすべてのトランザクションのタイプのトランザクションメタデータを確認し、アカウントが受け取ったXRPの金額をレポートします。
{% include '_code-samples/monitor-payments-websocket/js/read-amount-received.js' %}
{{ start_step("Read Payments") }} Start Reading
Transactions
次のステップ
- トランザクションの結果の確認で、トランザクションの実行内容を確認し、適切に対応するソフトウェアを構築します。
- あなた自身のアドレスからXRPの送金を試します。
- Escrow、ChecksまたはPayment Channelのような高度なタイプのトランザクションの監視と着信通知への応答を試します。
その他のプログラミング言語
多くのプログラミング言語には、WebSocket接続を使用して、データの送受信を行うためのライブラリが用意されています。JavaScript以外の言語でrippledのWebSocket APIとの通信を効率良く始めるには、同様な機能を利用している以下の例を参考にしてください。
Go
{% include '_code-samples/monitor-payments-websocket/go/monitor-incoming-payments.go' %}
ヒント: 目的のプログラミング言語の例がない場合があります。このページの最上部にある「GitHubで編集する」リンクをクリックして、作成したサンプルコードを提供してください。
脚注
1.実際には、HTTPベースのAPIを何度も呼び出す場合、クライアントとサーバーは複数の要求と応答を処理する際に同じ接続を再利用できます。この方法は、HTTP永続接続、またはキープアライブと呼ばれます。開発の観点から見ると、基本となる接続が新しい場合でも、再利用される場合でも、HTTPベースのAPIを使用するコードは同じです。
関連項目
- コンセプト:
- トランザクション
- 結果のファイナリティー - トランザクションの成功また失敗が最終的なものとなるタイミングを判断する方法(簡単な説明: トランザクションが検証済みレジャーにある場合は、その結果とメタデータは最終的なものです)。
- チュートリアル:
- リファレンス:
- トランザクションのタイプ
- トランザクションのメタデータ - メタデータフォーマットとメタデータに表示されるフィールドの概要
- トランザクションの結果 - トランザクションのすべての結果コードを掲載した表一覧
{% include '_snippets/rippled-api-links.md' %} {% include '_snippets/tx-type-links.md' %} {% include '_snippets/rippled_versions.md' %}