deBridge 백서

deBridge

원문

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

ypeScript examples. * Where affiliate fee parameters plug into the flow. * Tracking and observability via the Stats API for histories and per-swap lookups. * Freshness and slippage guidance for resilient UX at scale. > Reference: [DLN OpenAPI specification](/api-reference/single-chain-swap/get-v10chaintransaction). > Reference: [Stats API for order tracking](/api-reference/orders/get-filtered-list-of-orders-ordered-by-block-timestamp-desc-max-page-size:-100). *** ## Architecture in brief A same-chain swap never leaves its origin network. The DLN API handles route discovery and simulation, returning: * **EVM**: `tx` with `to`, `data`, and (when required) `value`, crafted to call **`DeBridgeRouter`**. * **Solana**: `tx.data` containing a hex-encoded `VersionedTransaction` that is deserialized, updated with a recent blockhash, signed, and sent. This design keeps the UI responsive before a wallet is connected, and returns an executable payload once sender and recipient are known. *** ## Endpoints ### Get a quote (estimation) Use **`GET /v1.0/chain/estimation`** to retrieve a quote for the desired pair. This step is suitable when the wallet is not connected or recipient is not yet known. **Minimal request - SOL for USDC on Solana** ```json theme={null} { "chainId": "7565164", "tokenIn": "11111111111111111111111111111111", // SOL on Solana "tokenInAmount": "200000", "tokenOut": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", // USDC on Solana, "slippage": "auto" // Default value } ``` <Note> * The response contains pricing, route details, aggregator comparison, and costs metadata used to inform UI and future submission. * The recommended value for slippage parameter is `auto`. The API selects a minimum reasonable slippage band from live market conditions and simulations. </Note> <Accordion title="Full response schema"> ```json theme={null} { "estimation": { "tokenIn": { "address": "string", // token address "name": "string", // token name "symbol": "string", // token symbol "decimals": 0, // token decimals "amount": "string", // input amount "approximateUsdValue": 0 // approximate USD value of input amount }, "tokenOut": { "address": "string", // token address "name": "string", // token name "symbol": "string", // token symbol "decimals": 0, // token decimals "amount": "string", // output amount "minAmount": "string", // minimum output amount "approximateUsdValue": 0 // approximate USD value of output amount }, "slippage": 0, // slippage percentage (e.g. 0.5 for 0.5%) "recommendedSlippage": 0, // recommended slippage percentage based on route simulation and volatility "protocolFee": "string", // protocol fee amount in tokenIn "estimatedTransactionFee": { // estimated transaction fee details "total": "string", "details": { "giveOrderState": "string", "giveOrderWallet": "string", "nonceMaster": "string", "txFee": "string", "priorityFee": "string", "gasLimit": "string", "gasPrice": "string", "baseFee": "string", "maxFeePerGas": "string", "maxPriorityFeePerGas": "string" }, "approximateUsdValue": 0 // approximate USD value of the total estimated transaction fee }, "costsDetails": [ // Breakdown of costs and fees { "chain": "string", "tokenIn": "string", "tokenOut": "string", "amountIn": "string", "amountOut": "string", "type": "string", "payload": { "feeAmount": "string", "feeBps": "string", "amountOutBeforeCorrection": "string", "estimatedVolatilityBps": "string", "actualFeeAmount": "string", "actualFeeBps": "string", "subsidyAmount": "string", "feeApproximateUsdValue": "string" } } ], "comparedAggregators": [ // List of queried aggregators and their rates { "name": "string", "amount": "string", "approximateUsdValue": 0, "priceDrop": 0, "imageUrl": "string" } ] } } ``` </Accordion> ### Get an executable transaction Use **`GET /v1.0/chain/transaction`** to obtain the **same quote fields** plus a **tx object** ready to be signed and broadcast. **Minimal request - USDC for MATIC on Polygon** ```json theme={null} { "chainId": "137", "tokenIn": "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359", // USDC on Polygon "tokenInAmount": "200000", "tokenOut": "0x0000000000000000000000000000000000000000", // Native token (MATIC on Polygon) "tokenOutRecipient": "<recipient_address>", "senderAddress": "<sender_address>", "slippage": "auto" // Default value } ``` **Response Highlights** ```json theme={null} { /* same content as in /estimation */ "tx": { "to": "<DeBridgeRouter_target_on_evm>", "data": "0x...", "value": "0x..." } } ``` On **Solana**, the `tx` object contains only: ```json theme={null} { /* same content as in /estimation */ "tx": { "data": "0x<hex_versioned_transaction>" } } ``` *** ## Compared Aggregators DLN’s same-chain swaps leverage multiple DeFi aggregators to ensure competitive pricing and route diversity. Response payload for both estimation and transaction endpoints includes the `comparedAggregators` field, which lists the aggregators queried during route discovery. This transparency allows integrators to understand the aggregator choice and provides insights into the liquidity sources considered for the swap. ## EVM submission flow The EVM submission sequence mirrors a typical ERC-20 flow plus a single call to `DeBridgeRouter`: * Fetch estimation with `/v1.0/chain/estimation` to present the quote. * Request transaction and quote via `/v1.0/chain/transaction` once the sender and recipient are known. * Ensure allowance for `tokenIn` toward `tx.to` - the `DeBridgeRouter` contract. [Deployed contracts](/dln-details/overview/deployed-contracts) page should be consulted for the correct address. * Send the main transaction using the returned `tx` object. **Skeleton (TypeScript) aligning with the provided example** ```typescript theme={null} // Pseudocode stitched to the structure of the provided EVM example const swap = await createDeBridgeSameChainSwap({ chainId: "137", // Polygon chainId tokenIn: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359", // USDC on Polygon tokenInAmount: "200000", tokenOut: "0x0000000000000000000000000000000000000000", // Native token (MATIC on Polygon) tokenOutRecipient: senderAddress, senderAddress }); // 1) Validate response const tx = swap?.tx; if (!tx?.to || !tx?.data) throw new Error("Invalid tx"); // 2) Approve if needed - only for ERC-20 tokenIn const required = BigInt(swap.tokenIn.amount); const currentAllowance = await erc20.allowance(senderAddress, tx.to); if (currentAllowance < required) { const approveTx = await erc20.approve(tx.to, required); await approveTx.wait(); } // 3) Submit the transaction const sent = await signer.sendTransaction(tx); const receipt = await sent.wait(); ``` #### Complete EVM example The full, production-ready script (logging, receipt checks, explorer links) is available [here](https://github.com/debridge-finance/api-integrator-example/tree/master/src/scripts/same-chain/poly-usdc-to-matic.ts) and can be reused for inspiration in real integrations. *** ## Solana submission flow The Solana variant returns a serialized `VersionedTransaction` ready to be deserialized, refreshed, signed, and sent: * Request transaction and quote via `/v1.0/chain/transaction` with Solana chain id. * Deserialize the hex `tx.data` into a `VersionedTransaction`. * Refresh `blockhash` with `getLatestBlockhash()` and set `tx.message.recentBlockhash`. * Optionally, adjust CU price/limit using a helper (as in the provided example). * Sign and send the raw transaction, then confirm. **Skeleton (TypeScript) aligning with the provided Solana example** ```typescript theme={null} const swap = await createDeBridgeSameChainSwap({ chainId: "7565164", // Solana chainId tokenIn: "11111111111111111111111111111111", // SOL on Solana tokenInAmount: "200000", tokenOut: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", // USDC on Solana tokenOutRecipient: solWallet.publicKey.toBase58(), senderAddress: solWallet.publicKey.toBase58() }); // Deserialize hex-encoded VersionedTransaction const tx = VersionedTransaction.deserialize(Buffer.from(swap.tx.data.slice(2), "hex")); // Refresh blockhash and (optionally) adjust CU price/limit, then sign const { blockhash } = await connection.getLatestBlockhash(); tx.message.recentBlockhash = blockhash; // updatePriorityFee(tx, NEW_CU_PRICE, NEW_CU_LIMIT); // as in the github example tx.sign([solWallet]); // Send and confirm const sig = await connection.sendRawTransaction(tx.serialize(), { skipPreflight: false }); ``` #### Complete Solana example The full script (simulation, CU sizing, prioritization fee median, and final submission) is available [here](https://github.com/debridge-finance/api-integrator-example/tree/master/src/scripts/same-chain/sol-usdc-to-sol.ts) and can be reused for inspiration in real integrations. *** ## Affiliate fees Affiliate fees are supported in the same-chain flow. The parameters used are `affiliateFeePercent` and `affiliateFeeRecipient`. More details are available in the the [Same-Chain Affiliate Fees article](/dln-details/affiliates/affiliate-fees#same-chain-affiliate-fees). <Note> The higher the affiliate fee, the worse rates the users using the app will get. </Note> *** ## Tracking and observability Tracking is performed with the [**Stats API**](). The default order history endpoints now include same-chain swaps when requested explicitly. ### Wallet histories (filtered list) For listing same-chain swaps of a single wallet `POST https://dln-api.debridge.finance/api/Orders/filteredList` should be used with a `filterMode: "SameChain"` parameter.\`: Allowed values for `filterMode` are: * `"CrossChain"` (default) * `"SameChain"` * `"Mixed"` **Example request** ```json theme={null} { "skip": 0, "take": 1, "maker": "<wallet_address>", "filterMode": "SameChain" } ``` <Accordion title="Example response"> ```json theme={null} { "orders": [ { "orderId": { /* order ID object - with bytes, bytes array and string values */ }, "creationTimestamp": 1759141461, // Unix timestamp "giveOfferWithMetadata": { "chainId": { /* chain ID object with different representations */ }, "tokenAddress": { /* token address object - with different representations */ }, "amount": { /* amount object - with different representations */ }, "metadata": { /* input token metadata */ "decimals": 6, "name": "Dephaser JPY", "symbol": "JPYT", "logoURI": null }, "decimals": 6, "name": "Dephaser JPY", "symbol": "JPYT", "logoURI": null }, "takeOfferWithMetadata": { "chainId": { /* chain ID object with different representations */ }, "tokenAddress": { /* token address object - with different representations */ }, "amount": { /* amount object - with different representations */ }, "metadata": { /* output token metadata */ "decimals": 18, "name": "AntHive", "symbol": "ANTH", "logoURI": null }, "decimals": 18, "name": "AntHive", "symbol": "ANTH", "logoURI": null }, "state": "Fulfilled", // Swap state "affiliateFee": { "beneficiarySrc": { /* affiliate fee beneficiary address object - with bytes, bytes array and string values */ }, "amount": { /* amount object - with bytes, bytes array and string values */ } }, "createEventTransactionHash": { /* transaction hash object - with bytes, bytes array and string values */ }, "tradeType": "SameChain" } ], "totalCount": 24 } ``` </Accordion> <Note> Same-chain swaps do not create an on-chain DLN order entity. The Stats API maps same-chain data into an order-like representation purely for consistency in histories and dashboards. </Note> ### Single order lookup To get details of a single order from the transaction hash, `GET https://dln-api.debridge.finance/api/SameChainSwap/${chainId}/tx/${transactionHash}` should be used with `chainId` and `transactionHash` parameters. Response structure is identical to the order object in the filtered list. *** ## Freshness and slippage Quotes are tied to current market conditions and route simulations. Signing and submission should occur shortly after a transaction payload is received; stale quotes should be refreshed **every 30 seconds**. The recommended value for `slippage` parameter is `"auto"`. The API selects a minimum reasonable slippage bound based on volatility and route simulation, a design that reduces execution risk without forcing conservative hard-coding. *** ## Example links * [EVM same-chain swap script (USDC → native on Polygon)](https://github.com/debridge-finance/api-integrator-example/tree/master/src/scripts/same-chain/poly-usdc-to-matic.ts). * [Solana same-chain swap script (USDC → native)](https://github.com/debridge-finance/api-integrator-example/tree/master/src/scripts/same-chain/sol-usdc-to-sol.ts). * [Estimation-only script demonstrating `/v1.0/chain/estimation`](https://github.com/debridge-finance/api-integrator-example/tree/master/src/scripts/same-chain/estimation/estimation-example.ts). * [Filtered history script using `api/Orders/filteredList` with `filterMode`](https://github.com/debridge-finance/api-integrator-example/tree/master/src/scripts/same-chain/queries/get-same-chain-swaps.ts). *** ## Production checklist * Fetch the `estimation` endpoint for quotes before the wallet is connected; request the `transaction` endpoint for quotes and a transaction object once `senderAddress` and `tokenOutRecipient` are known. * Prefer adaptive `slippage` with `auto`. * On EVM, ensure `tokenIn` allowance toward the `DeBridgeRouter` target in `tx.to`. * Refresh quotes every 30 seconds if signing is delayed to avoid staleness. * Use Stats API `filterList` endpoint with `filterMode: "SameChain"` for observability. # Same-Chain Swaps Source: https://docs.debridge.com/dln-details/integration-guidelines/same-chain-swaps/executive How DLN’s same-chain swaps work, what makes them reliable, and how to ship them fast. Same-chain swaps in DLN enable seamless token-for-token conversions on a single network. Instead of crossing chains, the operation remains localized, yet leverages the same design principles that drive DLN’s broader market order execution. Routing, simulation, and transaction construction are all part of the swap process where deBridge API does the heavy lifting, creating an efficient and resilient experience. The developers get to focus on building dapps, while deBridge ensures that users receive reliable quotes and executable transactions. Additionally, with [affiliate fees](/dln-details/integration-guidelines/same-chain-swaps/executive#affiliate-fees) supported, deBridge integrations can be monetized effectively. At a high level, the flow is straightforward: before a user connects their wallet to the app, an **estimation** request to the DLN API is used to fetch the quote for a chosen pair. Once the wallet is connected, the **transaction** endpoint should be used. It delivers the quote, just like the **estimation** endpoint, but with the addition of yielding a ready-to-submit payload, which completes the swap. Behind this simple sequence, the API carries out substantial work: it evaluates routes across several aggregators, reconciles live market conditions, and generates transactions structured to succeed in execution rather than exist as optimistic quotes. Dapps usually deal with slippage statically - they set it to some value and forget about it. This approach leads to subpar user experience when markets start shifting. With deBridge, users remain protected from adverse market effects with **adaptive slippage** as the core focus of same-chain swaps. After years of refinement, deBridge developed a way to set slippage dynamically, based on real-time conditions and route simulations. This mirrors DLN’s philosophy across all orders—providing both grounded estimates and final transaction calls from a single request sequence. For integrators, two immediate benefits emerge. First, there is no need to manually pre-compute complex slippage or routing logic. Second, the user experience remains responsive: an estimate can be fetched before wallet details are available, and then repeated with additional information to receive an executable payload. The API is intentionally designed to minimize latency - if the users like what they see, they can proceed to sign and submit quickly, because milliseconds matter. ### Reliability of quotes DLN’s API emphasizes "minimum reasonable" outcomes through market-aware protections. When intermediary swaps are required (for example, when moving between volatile assets and their paired counterparts), DeFi aggregators are queried and the route is simulated prior to returning calldata. The result is a quote grounded in what can be executed at the time of request, rather than an idealized price projection. Given that market conditions shift rapidly, the returned quotes carry a freshness expectation: **signing and submission should occur within approximately 30 seconds**, after which re-quoting is recommended. Interfaces that integrate DLN are therefore expected to encourage timely confirmations or refresh estimates automatically. ### Contracts and integration model On EVM chains, **same-chain swaps consistently route through the `DeBridgeRouter`**. The API abstracts away low-level venue interaction, delivering transaction objects that are pre-targeted and structured for execution. On Solana, the response is intentionally minimal: the `tx` field contains a single hex-encoded `VersionedTransaction` that can be deserialized and signed by wallets. ### Integration simplicity The same-chain swap process is designed to be as straightforward as possible, with a tight API surface that minimizes complexity and potential points of failure, ensuring a smooth integration experience and superb user experience. The flow relies on two key endpoints: * **`/v1.0/chain/estimation`** — provides a quote, usable prior to wallet connection or before recipient details are specified. * **`/v1.0/chain/transaction`** — repeats the request with wallet and recipient information, returning a ready-to-sign transaction object. Both are documented in the public [**OpenAPI reference**](/api-reference/single-chain-swap/get-v10chaintransaction). ### Adaptive slippage and slippage management Explicit slippage can be provided, but the recommended practice is to defer to the API’s automatic controls. DLN interprets `auto` as a dynamic guardrail derived from live conditions and route simulation, thus providing **adaptive slippage** in the response. This approach provides resilience in volatile markets, instead of relying on a slippage value that doesn't adapt to the market conditions. Manual overrides should be reserved for exceptional cases; otherwise, automatic limits ensure consistency and protection. ### Affiliate fees Affiliate fees transform same-chain swaps from a pure utility into a monetizable integration pathway. At the protocol level, every swap request can carry parameters that define both the affiliate fee percentage and the recipient of those fees. This ensures that each executed swap can simultaneously deliver value to end users and revenue back to the integrator. On EVM chains, settlement occurs automatically during the swap transaction execution. On Solana, integration leverages Jupiter’s referral infrastructure, where referral keys act as the designated recipient, and accumulated fees can be claimed via the Jupiter dashboard. Because affiliate fees are embedded in the request layer, no additional complexity is introduced to the swap flow itself. The estimation and transaction endpoints function as usual, with affiliate metadata included transparently. This design aligns with DLN’s guiding principle of minimizing integration friction while unlocking new revenue streams for integrators. ### Tracking and observability Swap outcomes are tracked through the **Stats API**. Queries can be performed using `filteredList` for wallet histories, or by trans
프로젝트로 돌아가기