XRP 백서

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 28쪽 중 26쪽

= b. multipliedBy ( "1.05" ). plus (min_bid) } else if (time_interval <= 19 ) { const t60 = BigNumber (time_interval). multipliedBy ( "0.05" ). exponentiatedBy ( 60 ) new_bid = b. multipliedBy ( "1.05" ). multipliedBy ( BigNumber ( 1 ). minus (t60) ). plus (min_bid) } const rounded_bid = new_bid. plus (lptokens). precision ( 15 , BigNumber. CEILING ). minus (lptokens). precision ( 15 , BigNumber. FLOOR ) return rounded_bid } SwapOut The SwapOut formula, defined in the XRPL-0030 specification as formula 10, calculates how much of one asset you have to swap in to the AMM to receive a target amount of the other asset out from the AMM. The following function implements SwapOut in JavaScript: JavaScript /* Implement the AMM SwapOut formula, as defined in XLS-30 section 2.4 AMM * Swap, formula 10. The asset weights WA/WB are currently always 1/1 so * they're canceled out. * C++ source: https://github.com/XRPLF/rippled/blob/2d1854f354ff8bb2b5671fd51252c5acd837c433/src/ripple/app/misc/AMMHelpers.h#L253-L258 * @param asset_out_bn BigNumber - The target amount to receive from the AMM. * @param pool_in_bn BigNumber - The amount of the input asset in the AMM's * pool before the swap. * @param pool_out_bn BigNumber - The amount of the output asset in the AMM's * pool before the swap. * @param trading_fee int - The trading fee as an integer {0, 1000} where 1000 * represents a 1% fee. * @returns BigNumber - The amount of the input asset that must be swapped in * to receive the target output amount. Unrounded, because * the number of decimals depends on if this is drops of * XRP or a decimal amount of a token; since this is a * theoretical input to the pool, it should be rounded * up (ceiling) to preserve the pool's constant product. */ export function swapOut ( asset_out_bn , pool_in_bn , pool_out_bn , trading_fee ) { return ( ( pool_in_bn. multipliedBy (pool_out_bn) ). dividedBy ( pool_out_bn. minus (asset_out_bn) ). minus (pool_in_bn) ). dividedBy ( feeMult (trading_fee)) } feeDecimal, feeMult, and feeMultHalf These helper functions are used in other AMM formulas to convert from a trading fee value in the ledger (integer from 0 to 1000) to a decimal representation that can be multiplied by a total to apply the fee. The following functions implement feeMult , feeMultHalf , and feeDecimal in JavaScript: JavaScript /* Convert a trading fee to a value that can be multiplied * by a total to "subtract" the fee from the total. * @param tFee int {0, 1000} * such that 1 = 1/100,000 and 1000 = 1% fee * @returns BigNumber (1 - fee) as a decimal */ function feeMult ( tFee ) { return BigNumber ( 1 ). minus ( feeDecimal (tFee) ) } /* Same as feeMult, but with half the trading fee. Single-asset deposits and * withdrawals use this because half of the deposit is treated as being * "swapped" for the other asset in the AMM's pool. * @param tFee int {0, 1000} * such that 1 = 1/100,000 and 1000 = 1% fee * @returns BigNumber (1 - (fee/2)) as a decimal */ function feeMultHalf ( tFee ) { return BigNumber ( 1 ). minus ( feeDecimal (tFee). dividedBy ( 2 ) ) } /* Convert a trading fee to a decimal BigNumber value, * for example 1000 becomes 0.01 * @param tFee int {0, 1000} * such that 1 = 1/100,000 and 1000 = 1% fee * @returns BigNumber(fee) as a decimal */ function feeDecimal ( tFee ) { const AUCTION_SLOT_FEE_SCALE_FACTOR = 100000 return BigNumber (tFee). dividedBy ( AUCTION_SLOT_FEE_SCALE_FACTOR ) } The AssetIn and SwapOut functions depend on these helper functions. solveQuadraticEq This helper function implements the quadratic equation in JavaScript: JavaScript /* Compute the quadratic formula. Helper function for ammAssetIn. * Params and return value are BigNumber instances. */ function solveQuadraticEq ( a , b , c ) { const b2minus4ac = b. multipliedBy (b). minus ( a. multipliedBy (c). multipliedBy ( 4 ) ) return ( b. negated (). plus (b2minus4ac. sqrt ()) ). dividedBy (a. multipliedBy ( 2 )) } The AssetIn formula depends on this. Conclusion Trading assets is never risk-free, and Automated Market Makers are no exception. However, the XRP Ledger's fast, low-cost transactions can be helpful in reducing the costs and fees associated with currency exchange. This tutorial demonstrates a minimal approach to using the auction slot to save money, but of course more creative uses are possible. The details depend on your specific circumstances and the types of trades you are doing, or expect to do in the future, as well as the state of the market, the XRP Ledger network, and the AMM instances in particular. See the Code Samples for additional related use cases, and feel free to contribute your own samples as well to show the community what can be done on the XRP Ledger. ## /docs/tutorials/javascript/build-apps/credential-issuing-service Build a Credential Issuing Service in Javascript Copy Requires the Credentials amendment . Loading... This tutorial demonstrates how to build and use a microservice that issues Credentials on the XRP Ledger, in the form of a RESTlike API, using the Express framework for Node.js. Prerequisites To complete this tutorial, you should meet the following guidelines: You have Node.js v18 or higher installed. You are somewhat familiar with modern JavaScript programming and have completed the Get Started Using JavaScript tutorial . You have some understanding of the XRP Ledger, its capabilities, and of cryptocurrency in general. Ideally you have completed the Basic XRPL guide . Setup First, download the complete sample code for this tutorial from GitHub: Credential Issuing Service sample code Then, in the appropriate directory, install the dependencies: npm install This should install appropriate versions of Express, xrpl.js and a few other dependencies. You can view all dependencies in the package.json file. To use the API that this microservice provides, you also need an HTTP client such as Postman , RESTED , or cURL . Overview The Credential Issuer microservice, mostly implemented in issuer_service.js , provides a RESTlike API with the following methods: Method Description POST /credential Request that the issuer issue a specific credential to a specific account. GET /admin/credential List all credentials issued by the issuer's address, optionally filtering only for credentials that have or have not been accepted by their subject. DELETE /admin/credential Delete a specific credential from the XRP Ledger, which revokes it. Note Some of the methods have /admin in the path because they are intended to be used by the microservice's administrator. However, the sample code does not implement any authentication. The sample code also contains a simple commmandline interface for a user account to accept a credential issued to it, as accept_credential.js . The other files contain helper code that is used by one or both tools. Usage 1. Get Accounts To use the credential issuing service, you need two accounts on the Devnet, where the Credentials amendment is already enabled. Go to the XRP Faucets page and select Devnet . Then, click the button to Generate credentials, saving the key pair (address and secret), twice. You will use one of these accounts as a credential issuer and the other account as the credential subject (holder), so make a note of which is which. 2. Start Issuer Service To start the issuer microservice, run the following command from the directory with the sample code: node issuer_service.js It should prompt you for your issuer account seed. Input the secret key you saved previously and press Enter. The output should look like the following: ✔ Issuer account seed: ✅ Starting credential issuer with XRPL address rPLY4DWhB4VA7PPZ8nvZLhShXeVZqeKif3 🔐 Credential issuer service running on port: 3005 Double-check that the XRPL address displayed matches the address of the credential issuer keys you saved earlier. 3. Request Credential To request a credential, make a request such as the following: Summary cURL HTTP method: POST URL: http://localhost:3005/credential Headers: Content-Type: application/json Request Body: { "subject" : "rBqPPjAW6ubfFdmwERgajvgP5LtM4iQSQG" , "credential" : "TestCredential" , "documents" : { "reason" : "please" } } The parameters of the JSON request body should be as follows: Field Type Required? Description subject String - Address Yes The XRPL classic address of the subject of the credential. Set this to the address that you generated at the start of this tutorial for the credential holder account. credential String Yes The type of credential to issue. The example microservice accepts any string consisting of alphanumeric characters as well as the special characters underscore ( _ ), dash ( - ), and period ( . ), with a minimum length of 1 and a maximum length of 64 characters. documents Object Yes As a credential issuer, you typically need to verify some confidential information about someone before you issue them a credential. As a placeholder, the sample code checks for a nested field named reason that contains the string please . expiration String - ISO8601 Datetime No The time after which the credential expires, such as 2025-12-31T00:00:00Z . uri String No Optional URI data to store with the credential. This data will become public on the XRP Ledger. If provided, this must be a string with minimum length 1 and max length 256, consisting of only characters that are valid in URIs, which are numbers, letters, and the following special characters: -._~:/?#[]@!$&'()*+,;=% . Conventionally, it should link to a Verifiable Credential document as defined by the W3C. This microservice immediately issues any credential that the user requests. A successful response from the API uses the HTTP status code 201 Created and has a response body with the result of submitting the transaction to the XRP Ledger. You can use the hash value from the response to look up the transaction using an explorer such as https://devnet.xrpl.org/ . Differences from Production For a real credential issuer, you would probably check the credential type and only issue specific types of credentials, or maybe even just one type. If checking the user's documents requires human intervention or takes longer than the amount of time an API request should wait to respond, you would need to store credential requests to some kind of storage, like a SQL database. You might also want to add a separate method for admins (or automated processes) to reject or issue the credential after checking the documents. 4. List Credentials To show a list of credentials issued by the issuing account, make the following request: Summary cURL HTTP method: GET URL: http://localhost:3005/admin/credential Query parameters (optional): Use ?accepted=yes to filter results to only credentials that the subject has accepted, or ?accepted=no for credentials the user has not accepted. A response could look like the following: { "credentials" : [ { "subject" : "rBqPPjAW6ubfFdmwERgajvgP5LtM4iQSQG" , "credential" : "TstCredential" , "accepted" : true } ] } In the response, each entry in the credentials array represents a Credential issued by the issuer account and stored in the blockchain. The details should match the request from the previous step, except that the documents are omitted because they are not saved on the blockchain. 5. Accept Credential For a credential to be valid, the subject of the credential has to accept it. You can use accept_credential.js to do this: node accept_credential.js It should prompt you for your subject account seed. Input the secret key you saved previously and press Enter. The script displays a list of Credentials that have been issued to your account and have not been accepted yet. Use the arrrow keys to scroll through the choices in the prompt and select the credential you want to accept, then press Enter. For example: ✔ Subject account seed: ? Accept a credential? 0) No, quit. 1) 'TstzzzCredential' issued by rPLY4DWhB4VA7PPZ8nvZLhShXeVZqeKif3 2) 'Tst9Credential' issued by rPLY4DWhB4VA7PPZ8nvZLhShXeVZqeKif3 ❯ 3) 'TCredential1' issued by rPLY4DWhB4VA7PPZ8nvZLhShXeVZqeKif3 4) 'Tst1Credential' issued by rPLY4DWhB4VA7PPZ8nvZLhShXeVZqeKif3 5) 'Tst0Credential' issued by rPLY4DWhB4VA7PPZ8nvZLhShXeVZqeKif3 6) 'Tst6Credential' issued by rPLY4DWhB4VA7PPZ8nvZLhShXeVZqeKif3 6. Revoke Credential To revoke an issued credential, make a request such as the following: Summary cURL HTTP method: DELETE URL: http://localhost:3005/admin/credential Headers: Content-Type: application/json Request Body: { "subject" : "rBqPPjAW6ubfFdmwERgajvgP5LtM4iQSQG" , "credential" : "TestCredential" } The parameters of the JSON request body should be as follows: Field Type Required? Description subject String - Address Yes The XRPL classic address of the subject of the credential to revoke. credential String Yes The type of credential to revoke. This must match a credential type previously issued. A successful response from the API uses the HTTP status code 200 OK and has a response body with the result of submitting the transaction to the XRP Ledger. You can use the hash value from the response to look up the transaction using an explorer. Code Walkthrough The code for this tutorial is divided among the following files: File Purpose accept_credential.js Commandline interface for a credential subject to look up and accept Credentials. credential.js Provides functions that validate credential input, verify supporting documents, and convert between the microservice’s simplified Credential format and the full XRPL representation of Credentials. errors.js Custom error classes that standardize how the server reports validation errors and XRPL transaction failures. issuer_service.js Defines the microservice as an Express app, including API methods and error handling. look_up_credentials.js A helper function for looking up Credentials tied to an account, including pagination and filtering, used by both the credential issuer and holder. accept_credential.js This file is meant to be run as a commandline tool so it starts with a shebang , followed by dependencies grouped by type: external packages (Node.js modules) first, and local modules last. #!/usr/bin/env node import dotenv from "dotenv" ; import inquirer from "inquirer" ; import { Client, Wallet } from "xrpl" ; import { lookUpCredentials } from "./look_up_credentials.js" ; import { hexToString } from "@xrplf/isomorphic/dist/utils/index.js" ; It returns a Wallet instance in the initWallet() function, with the subject account's key pair, using a seed either passed as an environment variable, or input as a password: const XRPL_SERVER = "wss://s.devnet.rippletest.net:51233" dotenv. config (); async function initWallet () { let seed = process.env. SUBJECT_ACCOUNT_SEED ; if ( ! seed) { const { seedInput } = await inquirer. prompt ([ { type: "password" , name: "seedInput" , message: "Subject account seed:" , validate : ( input ) => (input ? true : "Please specify the subject's master seed" ), }, ]); seed = seedInput; } return Wallet. fromSeed (seed); } The main() function contains the core logic for the script. At the begining of the function it sets up the XRPL client, and calls initWallet() to instantiate a Wallet object: async function main () { const client = new Client ( XRPL_SERVER ); await client. connect (); const wallet = await initWallet (); It then looks up pending credentials using the lookUpCredentials(...) function imported from look_up_credentials.js : const pendingCredentials = await lookUpCredentials ( client, "" , wallet.address, "no" ); Next is a text menu that displays each of the unaccepted credentials returned by the lookup, as well as the option to quit: const choices = pendingCredentials. map (( cred , i ) => ({ name: `${ i + 1 }) '${ hexToString ( cred . CredentialType ) }' issued by ${ cred . Issuer }` , value: i, })); choices. unshift ({ name: "0) No, quit." , value: - 1 }); const { selectedIndex } = await inquirer. prompt ([ { type: "list" , name: "selectedIndex" , message: "Accept a credential?" , choices, }, ]); if (selectedIndex === - 1 ) { process. exit ( 0 ); } If the user picked a credential, the code constructs a CredentialAccept transaction , signs and submits it, and waits for it to be validated by consensus before displaying the result. const chosenCred = pendingCredentials[selectedIndex]; const tx = { TransactionType: "CredentialAccept" , Account: wallet.address, CredentialType: chosenCred.CredentialType, Issuer: chosenCred.Issuer, }; console. log ( "Submitting transaction:" , tx); const response = await client. submit (tx, { autofill: true , wallet }); console. log ( "Response:" , response); await client. disconnect (); } Finally, the code runs the main() function: main (). catch (( err ) => { console. error ( "❌ Error:" , err.message); process. exit ( 1 ); }) issuer_service.js This file defines the Express app of the issuer microservice. It opens by importing dependencies, grouped into external packages and local files: import express from "express" ; import morgan from 'morgan' ; import inquirer from "inquirer" ; import dotenv from "dotenv" ; import { Wallet, Client } from "xrpl" ; import { validateCredentialRequest, verifyDocuments, credentialToXrpl, credentialFromXrpl, } from "./credential.js" ; import { XRPLTxError } from "./errors.js" ; import { lookUpCredentials } from "./look_up_credentials.js" ; It returns a Wallet instance in the initWallet() function, with the subject account's key pair, using a seed either passed as an environment variable, or input as a password: dotenv. config (); async function initWallet () { let seed = process.env. ISSUER_ACCOUNT_SEED ; if ( ! seed || seed. startsWith ( "<" )) { const { seedInput } = await inquirer. prompt ([ { type: "password" , name: "seedInput" , message: "Issuer account seed:" , validate : ( input ) => (input ? true : "Please specify the issuer's master seed" ), }, ]); seed = seedInput; } return Wallet. fromSeed (seed); } A function called handleAppError(...) is defined to handle errors thrown by the microservice. // Error handling -------------------------------------------------------------- function handleAppError ( res , err ) { if (err.name === "ValueError" ) { return res. status (err.status). json ({ error: err.type, error_message: err.message, }); } if (err.name === "XRPLTxError" ) { return res. status (err.status). json (err.body); } // Default fallback return res. status ( 400 ). json ({ error_message: err.message }); } The main() function contains the core logic for the script. At the begining of the function it sets up the XRPL client, and calls initWallet() to instantiate a Wallet object: async function main () { // Set up XRPL connection ------------------------------------------------------ const client = new Client ( "wss://s.devnet.rippletest.net:51233" ); await client. connect (); const wallet = await initWallet (); console. log ( "✅ Starting credential issuer with XRPL address" , wallet.address); Next, it creates the Express app: // Define Express app ------------------------------------------------------ const app = express (); app. use ( morgan ( 'common' )); // Logger app. use (express. json ()); // Middleware to parse JSON requests After that come the definitions for the three API methods, starting with POST /credential . Users c
프로젝트로 돌아가기