bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 31쪽 중 7쪽
ucted from the wallet placeholder amount. Rewards can't be native sol. Rewards are set by
the DLN API.
# Pubkey substituion
Determine which accounts in the instruction are input-dependent and cannot be passed directly from the user for security reasons.
For example, if there is a PDA in the destination network that depends on some unique transfer identifier, then we need to form `PubkeySubstitutions`
## Expenses
As well as pubkey substitutions, placeholders could be used to substitute extcall accounts, but placeholders can't be used to calculate ATA during
extcall execution. At the moment we have the following placeholders:
* **Wallet Placeholder**: `J4vKrc4pCdtiHpxFDfBy4iyZ22Uf7fBjJyJ817k4673y` - if you set this pubkey to some account, it will be replaced by actual
ExtcallWallet during execution. ExtcallWallet is a [token
account](https://github.com/solana-labs/solana-program-library/blob/523156a0cdd9cada27036bd72d326bc40c00f85f/token/program/src/state.rs#L83-L106) that
contains order's take tokens (in case take token is an SPL token. When native Sol is used ExtcallWallet will be empty).
* **ExtcallMetaPlacehoder**: `7cu34CRu47UZKLRHjt9kFPhuoYyHCzAafGiGWz83GNFs` will be replaced by ExtcallMeta. ExtcallMeta contains such info as order take
token, take token amount, execution state, orderId.
* **Authority Placeholder**: `2iBUASRfDHgEkuZ91Lvos5NxwnmiryHrNbWBfEVqHRQZ` will be replaced by ExtcallAuthority account during execution. Extcall authority
is an owner/authority account for ExtcallWallet. It is this account that manages [expenses](#expenses). When take token of the order is native Sol, funds will
be transferred here (not to the ExtcallWallet)
If both placeholder and substitution are used for the same account, only substitution will be performed.
# DataSubstitution
If you need a transfer amount as part of your transfer and it cannot be calculated in advance, then you must use `DataSubstitution`. One substitution is
now available (`SubmissionAuthWalletAmount`) which works as follows. Takes the `account_index` account of the current instruction, interprets it as a
token account, takes its balance, chooses its encoding (big endian, little endian), uses `substration` and inserts it into the current instruction by
`offset` before calling it.
# Calldata serialization
Instructions should be serialized one by one, final calldata is a concatenation of separately serialized instructions.
Solana's TransactionInstructions could be serialized into calldata format using
[`@debridge-finance/debridge-external-call`](https://www.npmjs.com/package/@debridge-finance/debridge-external-call) npm package:
<Accordion title="Calldata Serialization Example">
```typescript theme={null}
import * as wasm from "@debridge-finance/debridge-external-call";
import { PublicKey, TransactionInstruction } from "@solana/web3.js";
/**
* Substitutes amount at offset with `walletBalance(accounts[account_index]) - subtraction`
*/
type AmountSubstitution = {
/**
* big or little endian
*/
is_big_endian: boolean;
/**
* At what offset substitution should be done
*/
offset: number;
/**
* index of account in TransactionInstruction.keys to get balance for
*/
account_index: number;
/**
* Amount to deduct from wallet balance
*/
subtraction: number;
};
/**
* Since we don't know submissionAuth at the moment of calldata preparation we can prepare substitution to replace
* account at `index` with actual ATA(submissionAuth, tokenMint) during execution
*/
type WalletSubstitution = {
/**
* Token mint to calculate ATA for
*/
token_mint: string;
/**
* Account at this index will be replaced with ATA(submissionAuth, tokenMint) during execution
*/
index: number;
};
/**
* Structure required by wasm module
*/
interface IExtIx {
keys: {
pubkey: string;
isSigner: boolean;
isWritable: boolean;
}[];
data: Buffer;
programId: string;
}
function ixToIExtIx(ix: TransactionInstruction): IExtIx {
return {
keys: ix.keys.map((meta) => ({
pubkey: meta.pubkey.toBase58(),
isSigner: meta.isSigner,
isWritable: meta.isWritable,
})),
programId: ix.programId.toBase58(),
data: ix.data,
};
}
function serialize(
instruction: TransactionInstruction,
substitutions?: {
amountSubstitutions?: AmountSubstitution[];
walletSubstitutions?: WalletSubstitution[];
},
expense?: bigint,
reward?: bigint,
isInMandatoryBlock: boolean = false,
) {
const ixWrapper = new wasm.ExternalInstructionWrapper(
reward,
expense,
isInMandatoryBlock,
substitutions?.amountSubstitutions ?? [],
substitutions?.walletSubstitutions ?? [],
ixToIExtIx(instruction),
);
return ixWrapper.serialize();
}
const ix1: TransactionInstruction;
const ix2: TransactionInstruction;
const serializedIx1 = serialize(ix1, undefined, 1000n);
const serializedIx2 = serialize(ix2, undefined, 2000n);
const calldata = Buffer.concat([serializedIx1, serializedIx2 /** rest serialized instructions if any */]);
```
</Accordion>
# Order States
Source: https://docs.debridge.com/dln-details/integration-guidelines/order-creation/order-tracking-api/order-states
Order states explained. Order lifecycle state-machine diagram.
In the figure below, the order states are represented in a state-machine diagram, with the actions that trigger each state transition.
```mermaid theme={null}
stateDiagram-v2
%% --- states declared explicitly so we can style them ---
state Start
state End
state Created
state Fulfilled
state SentUnlock
state ClaimedUnlock
state OrderCancelled
state SentOrderCancelled
state ClaimedOrderCancel
%% --- initial entry ---
[*] --> Start
%% --- transitions from Start / Created ---
Start --> Created : Order Created on Source Chain
Created --> Fulfilled : Order Fulfilled on Destination Chain
Created --> OrderCancelled : Order Cancelled on Destination Chain
%% --- fulfilled path ---
Fulfilled --> SentUnlock : Cross-Chain Message Sent
SentUnlock --> ClaimedUnlock : Order Claimed by Solver
ClaimedUnlock --> End
%% --- cancelled path ---
OrderCancelled --> SentOrderCancelled : Cross-Chain Message Sent
SentOrderCancelled --> ClaimedOrderCancel : Order Claimed on Source Chain
ClaimedOrderCancel --> End
%% --- styling for Start / End nodes ---
style Start fill:#90EE90,stroke:#333,stroke-width:1px,color:#000
style End fill:#FF6347,stroke:#333,stroke-width:1px,color:#fff
```
According to the DLN API, an order must be in one of these states:
| State | Description |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Created** | An order placed by a user on the DLN is pending fulfillment. |
| **Fulfilled** | The order on the destination chain has been completed by a solver. The full amount of the requested assets has been successfully transferred to the `dstChainTokenOutRecipient`. |
| **SentUnlock** | After fulfilling the order, the solver initiates the unlock procedure on the destination chain. A cross-chain message is sent via DMP to unlock the input assets locked on the source chain. |
| **ClaimedUnlock** | The unlock process is finalized, and the solver receives the input assets. The affiliate fee is directed to the `affiliateFeeRecipient` on the source chain. |
| **OrderCancelled** | The `dstChainOrderAuthorityAddress` has started the cancellation process on the destination chain. |
| **SentOrderCancel** | A cross-chain message is sent via DMP from the destination to the source chain. It unlocks the input assets on the source chain to be claimed by the `srcAllowedCancelBeneficiary`. |
| **ClaimedOrderCancel** | The source chain input assets have been claimed by the `srcAllowedCancelBeneficiary`. The cancel procedure is finalized. |
# Tracking Orders
Source: https://docs.debridge.com/dln-details/integration-guidelines/order-creation/order-tracking-api/tracking-orders
Tracking Orders and their states via REST API.
***
# Tracking Orders via API
Once an order has been successfully created on-chain, its state can be monitored using several available methods, depending on the use case. For a
full overview of order states and their transitions, refer to the [Order
States](/dln-details/integration-guidelines/order-creation/order-tracking-api/order-states) documentation.
## Key Completion States
Orders progress through multiple internal states. However, from the perspective of the end-user experience, the following states indicate successful completion:
* `Fulfilled`
* `SentUnlock`
* `ClaimedUnlock`
<Tip>
Any of these states can be treated as successfully completed final states for application-level logic.
</Tip>
## Quick Start
* **Base URL:** `https://dln-api.debridge.finance`
* **Full endpoint reference:** [Swagger](/api-reference/orders/get-order-by-events-by-orderid)
* **Examples:** See the implementation examples in this [GitHub
repository](https://github.com/debridge-finance/api-integrator-example/tree/master/src/scripts/orders/queries).
## Querying Orders
### By Wallet Address
The [`POST /api/Orders/filteredList`](/api-reference/orders/get-filtered-list-of-orders-ordered-by-block-timestamp-desc-max-page-size:-100)
endpoint retrieves the current state and historical data for all orders associated with a wallet address. This endpoint is also used to populate the
trade history view in [deExplorer](https://app.debridge.com/orders).
Pagination is supported via `skip` and `take` parameters.
#### Example: Fetching Completed Orders for a Wallet
```ts theme={null}
const URL = 'https://dln-api.debridge.finance/api/Orders/filteredList';
const requestBody = {
orderStates: ['Fulfilled', 'SentUnlock', 'ClaimedUnlock'],
externalCallStates: ['NoExtCall'],
skip: 0,
take: 10,
maker: '0x441bc84aa07a71426f4d9a40bc40ac7183d124b9',
};
const data = await post(URL, requestBody);
```
#### Example: Filtering Completed Orders by Destination Chain (e.g. HyperEVM)
```ts theme={null}
const requestBody = {
giveChainIds: [],
takeChainIds: [100000022], // Internal HyperEVM Chain Id
orderStates: ['Fulfilled', 'SentUnlock', 'ClaimedUnlock'],
externalCallStates: ['NoExtCall'],
skip: 0,
take: 10,
maker: '0x441bc84aa07a71426f4d9a40bc40ac7183d124b9',
};
```
### By `referralCode`
Orders created through specific integrations can also be tracked by using the `referralCode` parameter attached to each API request.
```ts theme={null}
const requestBody = {
giveChainIds: [],
// All of these are considered to be fulfilled
// from the end-user's perspective
orderStates: ['Fulfilled', 'SentUnlock', 'ClaimedUnlock' ],
externalCallStates: ['NoExtCall'],
skip: 0,
take: 3,
referralCode: "31805",
};
```
### By Transaction Hash
For inspecting a specific order, use:
```
GET /api/Orders/creationTxHash/{hash}
```
**Example:**
> [https://dln-api.debridge.finance/api/Orders/creationTxHash/
> 0x3fe11542154f53dcf3134eacb30ea5ca586c9e134c223e56bbe1893862469bc5](https://dln-api.debridge.finance/api/Orders/creationTxHash/0x3fe11542154f53dcf3134eacb30ea5ca586c9e134c223e56bbe1893862469bc5)
<Warning>
If multiple orders were created in a single transaction, this endpoint returns data only for the **first** order.
</Warning>
#### Multiple Orders Created in the Same Transaction
To retrieve all order IDs:
```
GET /api/Transaction/{hash}/orderIds
```
**Example:**
> [https://dln-api.debridge.finance/api/Transaction/
> 0x40ee524d5bb9c4ecd8e55d23c66c5465a3f137be7ae24df366c3fd06daf7de7e
> /orderIds](https://dln-api.debridge.finance/api/Transaction/0xac3724d09ec7c1cdf3b6f845ce2fb6f84a8748d7f26f5f173c072cbaac6333ef/orderIds)
**Response:**
```json theme={null}
{
"orderIds": [
"0x9ee6c3d0aa68a7504e619b02df7c71539d0ce10e27f593bf8604b62e51955a01"
]
}
```
#### Example:
```ts theme={null}
export async function getOrderIdByTransactionHash(txHash: string) {
const URL = `https://dln-api.debridge.finance/api/Transaction/${txHash}/orderIds`;
const response = await fetch(URL);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to get orderIds: ${response.statusText}. ${errorText}`);
}
const data = await response.json();
if (data.error) {
throw new Error(`DeBridge API Error: ${data.error}`);
}
return data;
}
```
### By `orderId`
Use this endpoint:
```
GET /api/Orders/{orderId}
```
**Example:**
> [https://dln-api.debridge.finance/api/Orders/
> 0x9ee6c3d0aa68a7504e619b02df7c71539d0ce10e27f593bf8604b62e51955a01](https://dln-api.debridge.finance/api/Orders/0x9ee6c3d0aa68a7504e619b02df7c71539d0ce10e27f593bf8604b62e51955a01)
**Response:**
```json theme={null}
{
"status": "ClaimedUnlock"
}
```
#### Example:
```ts theme={null}
export async function getOrderStatusByOrderId(orderId: string) {
const URL = `https://dln-api.debridge.finance/api/Orders/${orderId}`;
const response = await fetch(URL);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to get order status: ${response.statusText}. ${errorText}`);
}
const data = await response.json();
if (data.error) {
throw new Error(`DeBridge API Error: ${data.error}`);
}
return data;
}
```
### Order Fulfillment Transaction
When order fulfillment transactions are important in the integration, they can be found inside of an each `order` returned by the API by referencing
the `fulfilledDstEventMetadata.transactionHash` field.
## Affiliate Fee Settlement
If set during order creation, the affiliate fee is automatically transferred to the `affiliateFeeRecipient` once the order reaches the `ClaimedUnlock`
status on EVM-based chains, and on Solana it is [manually withdrawable](/dln-details/affiliates/withdrawing-affiliate-fees).
# Submitting the Transaction
Source: https://docs.debridge.com/dln-details/integration-guidelines/order-creation/submitting-the-transaction
Learn how to submit a transaction using the deBridge Liquidity Network API – signing requirements, broadcasting, and practical examples.
# General
The transaction call retrieved from the DLN API must be signed by a user who is willing to sell the asset, and then broadcasted to the source chain.
# EVM
The `tx` object has the following structure and is ready to be signed and broadcasted:
```json theme={null}
{
"estimation": { ... },
"tx": {
"data": "0xfbe16ca70000000000000000000000000000000[...truncated...]",
"to": "0xeF4fB24aD0916217251F553c0596F8Edc630EB66",
"value": "5000000000000000",
},
}
```
Field names from the `tx` object are self-explanatory:
* `to` field defines where the transaction should be sent to, and typically you should expect the address of one of the smart contracts responsible
for forwarding;
* `data` field defines the transaction content, containing instructions related to swaps planned on the source or (and) on the destination chains,
bridging settings, etc;
* `value` is the amount of native blockchain currency that must be sent along with the transaction.
First, the `value` is always positive, even if the input token is an ERC-20 token. This is because the underlying DLN protocol takes a fixed amount in
the native currency, so the API always includes it as the transaction value. In the above example, the `value` equals the current fixed fee, which is
0.005 BNB on the BNB Chain.
Second, in case the input token is an ERC-20 token, a user needs to give approval to the smart contract address specified in the `tx.to` field prior
to submitting this transaction so it can transfer them on the behalf of the sender. This can be typically done by calling either `approve()` or
`increaseAllowance()` methods of the smart contract which implements the token you are willing to swap. Approve at least the amount that has been
specified as the `estimation.srcChainTokenIn.amount` response property.
Other than that, the transaction is ready to be signed by a user and broadcasted to the blockchain. It is also worth mentioning that the given
transaction data can be used as a part of another transaction: a dApp can bypass the given to, data and value to your smart contract, and make a
low-level call. There is even a possiblility to create multiple transactions for different orders, and perform several low-level calls.
<Note> The affiliate fee is paid only after the order gets fulfilled, and the taker requests order unlock during the unlock procedure. </Note>
# Solana
For DLN trades coming from Solana the `tx` object returned by DLN API has only one field - `data` which is hex-encoded
[VersionedTransaction](https://docs.solana.com/developing/versioned-transactions)
To convert the hex-encoded string into `VersionedTransaction` decode hex to buffer using any library and call
`VersionedTransaction.deserialize(decoded)`.
<Card title="Resources">
Make sure you properly set transaction priority fees based on the current load of the Solana network. Refer to one of these guides to learn more about
how to estimate tx fee parameters:
* [Triton guide](https://docs.triton.one/chains/solana/improved-priority-fees-api)
* [Helius guide](https://docs.helius.dev/solana-apis/priority-fee-api)
More info about sending versioned transactions
[here](https://docs.phantom.com/solana/sending-a-transaction-1#signing-and-sending-a-versioned-transaction).
</Card>
## Example
```typescript theme={null}
import { VersionedTransaction, Connection, clusterApiUrl, Keypair } from "@solana/web3.js";
function encodeNumberToArrayLE(num: number, arraySize: number): Uint8Array {
const result = new Uint8Array(arraySize);
for (let i = 0; i < arraySize; i++) {
result[i] = Number(num & 0xff);
num >>= 8;
}
return result;
}
function updatePriorityFee(tx: VersionedTransaction, computeUnitPrice: number, computeUnitLimit?: number) {
const computeBudgetOfset = 1;
const computeUnitPriceData = tx.message.compiledInstructions[1].data;
const encodedPrice = encodeNumberToArrayLE(computeUnitPrice, 8);
for (let i = 0; i < encodedPrice.length; i++) {
computeUnitPriceData[i + computeBudgetOfset] = encodedPrice[i];
}
if (computeUnitLimit) {
const computeUnitLimitData = tx.message.compiledInstructions[0].data;
const encodedLimit = encodeNumberToArrayLE(computeUnitLimit, 4);
for (let i = 0; i < encodedLimit.length; i++) {
computeUnitLimitData[i + computeBudgetOfset] = encodedLimit[i];
}
}
}
const wallet = new Keypair(); // your actual wallet here
const connection = new Connection(clusterApiUrl("mainnet-beta")); // your actual connection here
const tx = VersionedTransaction.deserialize(Buffer.from(tx.data.slice(2), "hex"));
// make sure to set correct CU price & limit for the best UX
updatePriorityFee(tx, NEW_CU_PRICE, NEW_CU_LIMIT);
const { blockhash } = await connection.getLatestBlockhash();
tx.message.recentBlockhash = blockhash; // Update blockhash!
tx.sign([wallet]); // Sign the tx with wallet
connection.sendTransaction(tx);
```
# Same-Chain Swaps
Source: https://docs.debridge.com/dln-details/integration-guidelines/same-chain-swaps/engineer
An engineering walkthrough for integrating DLN’s same-chain swaps with executable transactions, affiliate fees, and production-grade tracking.
A product surface wants single-network token conversions that behave like reliable transactions, not optimistic quotes. The integration path is
intentionally compact: first, ask for a quote; then, once the sender and recipient are known, request the fully constructed transaction. Under the
hood, DLN simulates routes across multiple aggregators and returns calldata that targets **`DeBridgeRouter`** on EVM, or a serialized transaction on
Solana. The result is an estimation-then-execution loop that stays responsive and grounded in market reality, with the added benefit of **adaptive
slippage** that takes real-time conditions into account.
### What this guide covers
* Endpoints and request shapes to obtain quotes and ready-to-send transactions.
* EVM and Solana submission flows based on the provided T프로젝트로 돌아가기