deBridge 백서

deBridge

원문

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

umber of block confirmations in the source chain aligns with their risk profile. For example, a solver may execute small orders as soon as they appear on the source chain, but wait for extra block confirmations in the case of an exceptionally large order; more complex rules can be applied to meet the needs of solvers. This also creates the potential to compete for orders that are not yet broadcasted, fulfilling them even BEFORE they are included on the source blockchain, which is a win-win case: users get to receive the exact amount of funds they have requested quickly, and professional market makers take profits according to their risk profiles without affecting users. * Risk of the cross-chain messaging infrastructure. The collusion of consensus participants is a trade-off that is born by all interoperability solutions without exception. The deBridge messaging infrastructure has a delegated staking and slashing module as part of the protocol design which prevents any theoretical collusion of validators. <img alt="Risk distribution diagram" /> # Use Cases Source: https://docs.debridge.com/dln-details/overview/use-cases Multiple ways of integration - which one is right? # Integration Overview There are several ways to integrate deBridge into your dApp, wallet, or protocol, depending on the specific use case. This section provides a high-level overview of the available integration methods: API, Widget, and Smart Contracts. # deBridge API Recommended for most production-grade integrations → Learn more about the API The deBridge API is the most robust and flexible integration method, abstracting away the complexities of cross-chain trading, smart contract interactions, and blockchain infrastructure. It provides RESTful endpoints to quote, create, and manage trades throughout their lifecycle. This improves transaction success rates and user experience, while reducing engineering overhead. Recommended if integrators: * Want full control over the UX/UI * Are building custom workflows or high-frequency trading logic * Need integration with backend infrastructure * Are targeting mobile-native or non-browser environments Use cases: Coming soon: examples such as exchange aggregators, non-custodial wallets, yield platforms, etc. # deBridge Widget Best for rapid integration and prototyping → Learn more about the Widget The deBridge Widget enables any web-based project to offer cross-chain swaps in minutes. It’s a pre-built UI component embeddable via iframe, fully customizable with themes, chains, tokens, and more. It also supports JavaScript-based event listeners and method calls for deeper interaction. Recommended if integrators: * Want a fast time-to-market with minimal development effort * Don’t need custom UX or transaction logic * Are building a frontend-heavy app, or integrating within a website or mobile WebView * Want to prototype or test before deeper integration Use cases: Coming soon: examples such as token swap pages, DeFi frontends, portfolio dashboards, etc. # Smart Contract Integration (DLN Protocol) Best for advanced and trustless DeFi integrations → Learn more about the DLN Protocol Smart Contracts The deBridge Liquidity Network (DLN) Protocol enables direct interaction with on-chain smart contracts to place and fulfill cross-chain limit orders. Developers can work directly with DlnSource and DlnDestination contracts for advanced decentralized workflows. This provides maximum flexibility, trustless execution, and fine-grained control. Recommended if integrators: * Need a fully decentralized integration with no off-chain components * Are building a protocol-level feature (e.g., DEX, bridge aggregator) * Want to operate as a solver or liquidity provider * Need deterministic on-chain behavior and verifiability Use cases: Coming soon: examples such as limit order protocols, liquidity relayers, solver networks, etc. # Deterministic Order ID Source: https://docs.debridge.com/dln-details/protocol-specs/deterministic-order-id How DLN order IDs are derived, including inputs and hash format. An order placed onto DLN is identified by a deterministic keccak256 hash derived from an array of bytes that contains all the properties of the order. The array is designed to be cross-chain compatible, so the smart contracts residing on both EVM and Solana can easily reproduce it. The smart contracts implementing the DLN protocol usually accept all these properties as a single data struct and derive an orderId programmatically to guarantee the order with the proper orderId is being managed. To get the deterministic orderId of the order, the array of bytes should contain its following properties: | Bytes | Bits | Field | | ----- | ---- | ------------------------------------------- | | 8 | 64 | Salt | | 1 | 8 | Maker Src Address Size (!=0) | | N | 8\*N | Maker Src Address | | 32 | 256 | Give Chain Id | | 1 | 8 | Give Token Address Size (!=0) | | N | 8\*N | Give Token Address | | 32 | 256 | Give Amount | | 32 | 256 | Take Chain Id | | 1 | 8 | Take Token Address Size (!=0) | | N | 8\*N | Take Token Address | | 32 | 256 | Take Amount | | 1 | 8 | Receiver Dst Address Size (!=0) | | N | 8\*N | Receiver Dst Address | | 1 | 8 | Give Patch Authority Address Size (!=0) | | N | 8\*N | Give Patch Authority Address | | 1 | 8 | Order Authority Address Dst Size (!=0) | | N | 8\*N | Order Authority Address Dst | | 1 | 8 | Allowed Taker Dst Address Size | | N | 8\*N | \* Allowed Taker Address Dst | | 1 | 8 | Allowed Cancel Beneficiary Src Address Size | | N | 8\*N | \* Allowed Cancel Beneficiary Address Src | | 1 | 8 | Is Hook Presented 0x0 - Not, != 0x0 - Yes | | 32 | 256 | \* Hook Envelope Hash | # EVM Chains Hook Anatomy Source: https://docs.debridge.com/dln-details/protocol-specs/evm-chains-hook-anatomy Learn about EVM Chain Hook Anatomy – Envelope v1, Hook data V1 layout, and Universal Hook. During order fulfillment the `DlnDestination` smart contract performs standard routine procedures, including checking that the order is still open (neither Fulfilled nor Cancelled) and that the requested amount of tokens were successfully pulled from the solver. Finally, it transfers the requested amount of tokens to the order's recipient address, OR — if the hook raw data is provided — to the `DlnExternalCallAdapter` hook engine smart contract address (accessible via `DlnDestination.externalCallAdapter`), immediately invoking it for hook handling. `DlnExternalCallAdapter` is responsible for proper hook raw data decoding, hook execution, and guaranties that hook behavior conforms given properties. # Hook data V1 layout DlnExternalCallAdapter expects the hook raw data (called externalCallEnvelope) to be an concatenation of two encodePacked'd data types, specifically: * first byte: `uint8 envelopeVersion` * subsequent bytes: `bytes envelopeData` The `envelopeVersion` determines which data structure was used to encode the `envelopeData`. ## Envelope v1 The `envelopeVersion=1` is currently the only available version, and its corresponding structure for the `envelopeData` is `HookDataV1` as follows: ```solidity theme={null} struct HookDataV1 { // Address that will receive order outcome if the hook gets reverted. // Mandatory for optional-success hooks address fallbackAddress; // The address of a smart contract that acts as a hook target. // Must implement the IExternalCallExecutor interface address target; // Optional reward to pay to a solver who executes the hook // Reward is being cut off the order outcome. // Reasonable (but not mandatory) for non-atomic hooks uint160 reward; // False: atomic hook // True: non-atomic hook bool isNonAtomic; // False: optional-success hook // True: success-required hooks bool isSuccessRequired; // Arbitrary data to be passed to the target during the call bytes targetPayload; } ``` HookDataV1.target defines a target smart contract address that would get called by the DlnExternalCallAdapter hook engine smart. The target smart contract MUST implement the IExternalCallExecutor interface with only two functions: onEtherReceived() and onERC20Received() — that get called (along with order details and the payload) right after the native or ERC-20 token got transferred to it: <Accordion title="IExternalCallExecutor"> ```solidity theme={null} interface IExternalCallExecutor { /** * @notice Handles the receipt of Ether to the contract, then validates and executes a function call. * @dev Only callable by the adapter. This function decodes the payload to extract execution data. * If the function specified in the callData is prohibited, or the recipient contract is zero, * all Ether is transferred to the fallback address. * Otherwise, it attempts to execute the function call. Any remaining Ether is then transferred to the fallback address. * @param _orderId The ID of the order that triggered this function. * @param _fallbackAddress The address to receive any unspent Ether. * @param _payload The encoded data containing the execution data. * @return callSucceeded A boolean indicating whether the call was successful. * @return callResult The data returned from the call. */ function onEtherReceived( bytes32 _orderId, address _fallbackAddress, bytes memory _payload ) external payable returns (bool callSucceeded, bytes memory callResult); /** * @notice Handles the receipt of ERC20 tokens, validates and executes a function call. * @dev Only callable by the adapter. This function decodes the payload to extract execution data. * If the function specified in the callData is prohibited, or the recipient contract is zero, * all received tokens are transferred to the fallback address. * Otherwise, it attempts to execute the function call. Any remaining tokens are then transferred to the fallback address. * @param _orderId The ID of the order that triggered this function. * @param _token The address of the ERC20 token that was transferred. * @param _transferredAmount The amount of tokens transferred. * @param _fallbackAddress The address to receive any unspent tokens. * @param _payload The encoded data containing the execution data. * @return callSucceeded A boolean indicating whether the call was successful. * @return callResult The data returned from the call. */ function onERC20Received( bytes32 _orderId, address _token, uint256 _transferredAmount, address _fallbackAddress, bytes memory _payload ) external returns (bool callSucceeded, bytes memory callResult); } ``` </Accordion> For orders buying ERC-20 token, the DlnExternalCallAdapter first transfers the token's amount to the hook's target, then invokes its onERC20Received() method: ```solidity theme={null} IERC20(order.takeToken).safeTransfer(hook.target, order.takeAmount); IExternalCallExecutor(hook).onERC20Received(..., hook.targetPayload); ``` For orders buying native blockchain currency (ether, etc), the DlnExternalCallAdapter invokes the hook's target.onEtherReceived() method along with the amount of native currency as a msg.value: ```solidity theme={null} IExternalCallExecutor(hook).onEtherReceived{ value: order.takeAmount }(..., hook.targetPayload); ``` # Universal Hook One the common ways to build cross-chain interactions is to make calls to arbitrary existing contracts, without the need to introduce custom intermediaries (smart contracts that act as hooks). To facilitate this need, we've build a default Universal Hook — a pre-deployed implementation of the IExternalCallExecutor and a part of the DLN deployment — that can act as a hook's target and is designed to transparently execute arbitrary transaction calls bypassed through its targetPayload. To reuse this hook, HookDataV1's target must be set to address(0) (this would tell the DlnExternalCallAdapter hook engine to switch to the universal hook as a default hook implementation), and HookDataV1's targetPayload must represent the following encoded data struct: ```solidity theme={null} struct UniversalHookPayload { address to; uint32 txGas; bytes callData; } ``` When called, the universal hook would makes a CALL to the given to address using the given callData. The transfer of native blockchain currency is performed during the call itself: ```solidity theme={null} payload.to.call{ gas: payload.txGas, value: order.takeAmount }(payload.callData); ``` Mind that ERC-20 token transfer during transaction call made by the Universal hook behaves differently: the universal hook does not transfer the token to the to address (like the DlnExternalCallAdapter does when calling a hook's target), but sets a temporary allowance instead before making a call, and reverts it back after the call: ```solidity theme={null} IERC20(order.takeToken).approve(payload.to, order.takeAmount); // payload.to must pull the tokens from the caller, using the size of the // allowance as a reference amount payload.to.call{ gas: payload.txGas }(payload.callData); IERC20(order.takeToken).approve(payload.to, 0); // the remainder not consumed by the payload.to is transferred to the fallback address ``` If the payload.to had pulled less amount than the order's outcome, the remainder is transferred to the given fallback address automatically. If the call to the payload.to target gets reverted, the execution bubbles up to the DlnExternalCallAdapter hook engine who handles this failure according to the hook's properties (revert entire call if the hook is a success-required hook; gracefully ignore the failure if the hook is a success-optional hook). # Hook Data Source: https://docs.debridge.com/dln-details/protocol-specs/hook-data Structure and encoding of hook data attached to DLN orders. Hooks are on-chain actions that can be optionally attached to an order upon its creation, and become the inseparable and cryptographically signed part of it, and are executed on the destination chain upon order fulfillment. An action can perform actions of any complexity, including operations on the outcome of the order. Orders are identified by [deterministic order ID](/dln-details/protocol-specs/deterministic-order-id), and the hash of the hook's raw data is essentially a part of this ID (see the last two fields of the deterministic order ID reference), so once a user signs-off an order with a hook, he eventually makes a cryptographic confirmation that he is willing to sell input asset for output asset AND execute a specific action along with the output asset on the destination chain. The proper execution of the hook during order fulfillment is guaranteed by [`DlnDestination`](/dln-details/overview/deployed-contracts) — the DLN smart contract responsible for filling orders, which ensures that the given hook along with other properties of the order actually match the given order ID. This means that trying to spoof a hook would lead to a different ID of a non-existent order, so the solver is compelled to pass a specific hook data, otherwise they would fill the non-existent order and eventually lose given funds forever. The raw data itself is not generalized, which allows the implementations of the `DlnDestination` smart contract for different blockchain engines impose different and platform-specific requirements. Further reading: * [Anatomy of a Hook for the EVM-based chains](/dln-details/protocol-specs/evm-chains-hook-anatomy) * [Anatomy of a Hook for Solana](/dln-details/protocol-specs/solana-hook-anatomy) # Solana Hook Anatomy Source: https://docs.debridge.com/dln-details/protocol-specs/solana-hook-anatomy Solana hook transaction layout and instruction requirements. The hook raw data intended for Solana is represented as a versioned transaction with one or more instructions. Thus, only *non-atomic success-required hooks* are supported. To craft a proper versioned transaction, use the guide: [Creating Hook data for Solana](/dln-details/integration-guidelines/order-creation/hooks/solana-hook-data) # Custom Linking Source: https://docs.debridge.com/dln-details/widget/app Create custom no-code deBridge app links with preset swap parameters and referral codes. The deBridge web application enables users to create custom links with a pre-defined set of parameters using URL query parameters. Users and developers can use their own prefilled settings for deSwap or dePort.​ | **Parameter** | **Description** | | ---------------- | -------------------------------------------------------------------------------------- | | `inputChain` | ID of the chain where deSwap is initiated. | | `inputCurrency` | Token contract address of the input currency that will be swapped for output currency. | | `outputChain` | ID of the destination chain. | | `outputCurrency` | Token contract address of the output currency that input currency will be swapped for. | | `r` | Your generated referral code. | | `address` | Recipient address. | | `amount` | Token amount to swap. | # Example ``` https://app.debridge.com/deswap?inputChain=&inputCurrency=&outputChain=&outputCurrency=&r=&address=&amount= ``` ## deSwap BSC(USDC) - ETHEREUM (USDT) ``` ​https://app.debridge.com/deswap?inputChain=56&inputCurrency=0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d&outputChain=1&outputCurrency=0xdac17f958d2ee523a2206206994597c13d831ec7&r=111&address=0x0000000000000000000000000000000000000000​ ``` ## dePort BSC(USDC) - deUsdc ``` ​https://app.debridge.com/deport?inputChain=56&inputCurrency=0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d&r=111 ``` # Chains and Tokens ID The Chain IDs of all chains can be found at [https://chainlist.org/](https://chainlist.org/) or in the spreadsheet below: | **ID** | **Chain** | **Token Request** | | ------- | ------------------- | ---------------------------------------- | | `1` | Ethereum | `GET https://tokens.1inch.io/v1.1/1` | | `56` | Binance Smart Chain | `GET https://tokens.1inch.io/v1.1/56` | | `128` | Heco | `GET https://tokens.1inch.io/v1.1/128` | | `137` | Polygon | `GET https://tokens.1inch.io/v1.1/137` | | `42161` | Arbitrum | `GET https://tokens.1inch.io/v1.1/42161` | | `43114` | Avalanche | `GET https://tokens.1inch.io/v1.1/43114` | | `250` | Fantom | `GET https://tokens.1inch.io/v1.1/250` | # deBridge Widget Source: https://docs.debridge.com/dln-details/widget/deBridge-widget deBridge Widget - a customizable, drop-in UI component for cross-chain swaps. Learn about its features, integration steps, and event handling. With just a few lines of code, all projects and developers can embed a cross-chain exchange between arbitrary assets within your app (mobile app, website, dApp, etc.) based on the deBridge protocol. You can make the deBridge widget part of your app and you're fully free to customize colors, fonts, chains, and tokens according to your design and preferences. <img alt="Widget Image" /> # Requirements The widget is based on web technology, that's why your app must support technology such as JavaScript, HTML, CSS or use webView to add the widget. You can use any type of framework for the web app. The launch of the widget is going on through iframe embedded on the page. The API integration is based on JavaScript. # Widget embedding The following steps are needed to add the widget: * Connect js script to your app ```html theme={null} <script src="https://app.debridge.com/assets/scripts/widget.js"></script> ``` * Add an html element with a unique id * Generate js object with the description of the widget settings. You can use the [builder](https://app.debridge.com/widget) of deSwap Widget for auto-generation js object. * Initialize `deBridge.widget(initObject)`, where `initObject` contains the settings. Initializing must be executed after connection from step 1. # Widget object settings description | **Parameter** | **Type** | **Description** | | ---------------- | -------- | ------------------------------------------------------------------------------------------ | | `element` | `string` | **(mandatory)** – Unique ID of the HTM
프로젝트로 돌아가기