A typescript multichain client for atomiqlabs trustlesss cross-chain swaps.
npm install @atomiqlabs/sdk
Set Solana RPC URL to use
const solanaRpc = "https://api.mainnet-beta.solana.com";
This uses browser's Indexed DB by default
const swapper: MultichainSwapper = new MultichainSwapper({
chains: {
SOLANA: {
rpcUrl: solanaRpc
}
}
});
For NodeJS we need to explicitly use filsystem storage
const swapper: MultichainSwapper = new MultichainSwapper({
chains: {
SOLANA: {
rpcUrl: solanaRpc
}
},
//The following line is important for running on backend node.js,
// because the SDK by default uses browser's Indexed DB
storageCtor: (name: string) => new FileSystemStorageManager(name)
});
//React, using solana wallet adapter
const anchorWallet = useAnchorWallet();
const wallet = new SolanaSigner(anchorWallet);
or
//Creating a wallet from scratch
const signer = Keypair.fromSecretKey(_privateKey); //Or Keypair.generate() to generate new one
const wallet = new SolanaSigner(signer);
Initialize the swapper
await swapper.init();
Now we have the multichain swapper initialized
To make it easier to do swaps between bitcoin and a specific chain we can extract a chain-specific swapper, and also set a signer.
const solanaSwapper = swapper.withChain("SOLANA").withSigner(signer);
Initiating & executing the swap.
const _exactIn = false; //exactIn = false, so we specify the output amount
const _amount = new BN(10000); //Amount in BTC base units - sats
const _address = "bc1qtw67hj77rt8zrkkg3jgngutu0yfgt9czjwusxt"; //BTC address of the recipient
//Create the swap: swapping SOL to Bitcoin on-chain, receiving _amount of satoshis (smallest unit of bitcoin) to _address
const swap = await solanaSwapper.create(
Tokens.SOLANA.SOL,
Tokens.BITCOIN.BTC,
_amount,
_exactIn,
_address
);
//Get the amount required to pay and fee
const amountToBePaid: string = swap.getInput().amount; //Human readable amount to be paid on the Solana side (including fee)
const fee: string = swap.getFee().amountInSrcToken.amount; //Human readable swap fee paid on the Solana side (already included in the the above amount)
//Get swap expiration time
const expiry: number = swap.getExpiry(); //Expiration time of the swap in UNIX milliseconds, swap needs to be initiated before this time
//Initiate and pay for the swap
await swap.commit();
//Wait for the swap to conclude
const result: boolean = await swap.waitForPayment();
if(!result) {
//Swap failed, money can be refunded
await swap.refund();
} else {
//Swap successful, we can get the bitcoin txId
const bitcoinTxId = swap.getBitcoinTxId();
}
- ToBTCSwapState.REFUNDED = -3
- Swap failed and was successfully refunded
- ToBTCSwapState.QUOTE_EXPIRED = -2
- Swap quote expired and cannot be executed anymore
- ToBTCSwapState.QUOTE_SOFT_EXPIRED = -1
- Swap quote soft-expired (i.e. the quote probably expired, but if there is already an initialization transaction sent it might still succeed)
- ToBTCSwapState.CREATED = 0
- Swap quote is created, waiting to be executed
- ToBTCSwapState.COMMITED = 1,
- Swap was initiated (init transaction sent)
- ToBTCSwapState.SOFT_CLAIMED = 2,
- Swap was processed by the counterparty but not yet claimed on-chain (bitcoin transaction was sent, but unconfirmed yet)
- ToBTCSwapState.CLAIMED = 3
- Swap was finished and funds were successfully claimed by the counterparty
- ToBTCSwapState.REFUNDABLE = 4
- Swap was initiated but counterparty failed to process it, the user can now refund his funds
Initiating & executing the swap.
const _exactIn = true; //exactIn = true, so we specify the input amount
const _amount = new BN(10000); //Amount in BTC base units - sats
//Create the swap: swapping _amount of satoshis of Bitcoin on-chain to SOL
const swap = await solanaSwapper.create(
Tokens.BITCOIN.BTC,
Tokens.SOLANA.SOL,
_amount,
_exactIn
);
//Get the amount required to pay, amount to be received and fee
const amountToBePaidOnBitcoin: string = swap.getInput().amount; //Human readable amount of BTC that needs to be send to the BTC swap address
const amountToBeReceivedOnSolana: string = swap.getOutput().amount; //Human readable amount SOL that will be received on Solana
const fee: string = swap.getFee().amountInSrcToken.amount; //Human readable fee in BTC
//Get swap offer expiration time
const expiry: number = swap.getExpiry(); //Expiration time of the swap offer in UNIX milliseconds, swap needs to be initiated before this time
//Get security deposit amount (Human readable amount of SOL that needs to be put down to rent the liquidity from swap intermediary), you will get this deposit back if the swap succeeds
const securityDeposit: string = swap.getSecurityDeposit().amount;
//Get claimer bounty (Human readable amount of SOL reserved as a reward for watchtowers to claim the swap on your behalf)
const claimerBounty: string = swap.getClaimerBounty().amount;
//Once client is happy with swap offer, we can send a Solana transaction that initiates the swap by opening a bitcoin swap address
await swap.commit();
//Get the bitcoin address
const receivingAddressOnBitcoin = swap.getAddress();
//Get the QR code data (contains the address and amount)
const qrCodeData = swap.getQrData(); //Data that can be displayed in the form of QR code
//Get the bitcoin swap address timeout (in UNIX millis), a transaction needs to be made in under this time
const expiryTime = swap.getTimeoutTime();
try {
//Wait for the payment to arrive
await swap.waitForPayment(
null, null,
(
txId: string, //Transaction ID of the received bitcoin transaction
confirmations: number, //Current confirmations of the transaction
targetConfirmations: number, //Required confirmations
transactionETAms: number //Estimated in time (in milliseconds) until when the transaction will receive required amount of confirmations
) => {
//Callback for transaction updates
}
);
//Swap will get automatically claimed by the watchtowers
await swap.waitTillClaimed();
} catch(e) {
//Error occurred while waiting for payment
}
- FromBTCSwapState.EXPIRED = -3
- Bitcoin swap address expired
- FromBTCSwapState.QUOTE_EXPIRED = -2
- Swap quote expired and cannot be executed anymore
- FromBTCSwapState.QUOTE_SOFT_EXPIRED = -1
- Swap quote soft-expired (i.e. the quote probably expired, but if there is already an initialization transaction sent it might still succeed)
- FromBTCSwapState.PR_CREATED = 0
- Swap quote is created, waiting for the user to open a bitcoin swap address
- FromBTCSwapState.CLAIM_COMMITED = 1
- Bitcoin swap address is opened
- FromBTCSwapState.BTC_TX_CONFIRMED = 2
- Bitcoin transaction sending funds to the swap address is confirmed
- FromBTCSwapState.CLAIM_CLAIMED = 3
- Swap funds are claimed to the user's wallet
//Destination lightning network invoice, amount needs to be part of the invoice!
const _lightningInvoice = "lnbc10u1pj2q0g9pp5ejs6m677m39cznpzum7muruvh50ys93ln82p4j9ks2luqm56xxlshp52r2anlhddfa9ex9vpw9gstxujff8a0p8s3pzvua930js0kwfea6scqzzsxqyz5vqsp5073zskc5qfgp7lre0t6s8uexxxey80ax564hsjklfwfjq2ew0ewq9qyyssqvzmgs6f8mvuwgfa9uqxhtza07qem4yfhn9wwlpskccmuwplsqmh8pdy6c42kqdu8p73kky9lsnl40qha5396d8lpgn90y27ltfc5rfqqq59cya";
//Create the swap: swapping SOL to Bitcoin lightning
const swap = await solanaSwapper.create(
Tokens.SOLANA.SOL,
Tokens.BITCOIN.BTCLN,
null,
false,
_lightningInvoice
);
//Get the amount required to pay and fee
const amountToBePaid: string = swap.getInput().amount; //Human readable amount to be paid on the Solana side (including fee)
const fee: string = swap.getFee().amountInSrcToken.amount; //Human readable swap fee paid on the Solana side (already included in the the above amount)
//Get swap expiration time
const expiry: number = swap.getExpiry(); //Expiration time of the swap in UNIX milliseconds, swap needs to be initiated before this time
//Initiate and pay for the swap
await swap.commit();
//Wait for the swap to conclude
const result: boolean = await swap.waitForPayment();
if(!result) {
//Swap failed, money can be refunded
await swap.refund();
} else {
//Swap successful, we can get the lightning payment secret pre-image, which acts as a proof of payment
const lightningSecret = swap.getSecret();
}
- ToBTCSwapState.REFUNDED = -3
- Swap failed and was successfully refunded
- ToBTCSwapState.QUOTE_EXPIRED = -2
- Swap quote expired and cannot be executed anymore
- ToBTCSwapState.QUOTE_SOFT_EXPIRED = -1
- Swap quote soft-expired (i.e. the quote probably expired, but if there is already an initialization transaction sent it might still succeed)
- ToBTCSwapState.CREATED = 0
- Swap quote is created, waiting to be executed
- ToBTCSwapState.COMMITED = 1,
- Swap was initiated (init transaction sent)
- ToBTCSwapState.SOFT_CLAIMED = 2,
- Swap was processed by the counterparty but not yet claimed on-chain (lightning network payment secret was revealed)
- ToBTCSwapState.CLAIMED = 3
- Swap was finished and funds were successfully claimed by the counterparty
- ToBTCSwapState.REFUNDABLE = 4
- Swap was initiated but counterparty failed to process it, the user can now refund his funds
const _exactIn = true; //exactIn = true, so we specify the input amount
const _amount = new BN(10000); //Amount in BTC base units - sats
//Create the swap: swapping _amount of satoshis from Bitcoin lightning network to SOL
const swap = await solanaSwapper.create(
Tokens.BITCOIN.BTCLN,
Tokens.SOLANA.SOL,
_amount,
_exactIn
);
//Get the bitcoin lightning network invoice (the invoice contains pre-entered amount)
const receivingLightningInvoice: string = swap.getLightningInvoice();
//Get the QR code (contains the lightning network invoice)
const qrCodeData: string = swap.getQrData(); //Data that can be displayed in the form of QR code
//Get the amount required to pay, amount to be received and fee
const amountToBePaidOnBitcoin: string = swap.getInput().amount; //Human readable amount of BTC that needs to be send to the BTC swap address
const amountToBeReceivedOnSolana: string = swap.getOutput().amount; //Human readable amount SOL that will be received on Solana
const fee: string = swap.getFee().amountInSrcToken.amount; //Human readable fee in BTC
try {
//Wait for the lightning payment to arrive
await swap.waitForPayment();
//Claim the swap funds - this will initiate 2 Solana transactions
await swap.commitAndClaim();
} catch(e) {
//Error occurred while waiting for payment
}
- FromBTCLNSwapState.FAILED = -4
- If the claiming of the funds was initiated, but never concluded, the user will get his lightning network payment refunded
- FromBTCLNSwapState.QUOTE_EXPIRED = -3
- Swap quote expired and cannot be executed anymore
- FromBTCLNSwapState.QUOTE_SOFT_EXPIRED = -2
- Swap quote soft-expired (i.e. the quote probably expired, but if there is already an initialization transaction sent it might still succeed)
- FromBTCLNSwapState.EXPIRED = -1
- Lightning network invoice expired, meaning the swap is expired
- FromBTCLNSwapState.PR_CREATED = 0
- Swap is created, the user should now pay the provided lightning network invoice
- FromBTCLNSwapState.PR_PAID = 1
- Lightning network invoice payment was received (but cannot be settled by the counterparty yet)
- FromBTCLNSwapState.CLAIM_COMMITED = 2
- Claiming of the funds was initiated
- FromBTCLNSwapState.CLAIM_CLAIMED = 3
- Funds were successfully claimed & lightning network secret pre-image revealed, so the lightning network payment will settle now
You can get the current state of the swap with:
const state = swap.getState();
You can also set a listener to listen for swap state changes:
swap.events.on("swapState", swap => {
const newState = swap.getState();
});
For the meaning of the states please refer to the "Swap state" section under each swap type.
LNURLs extend the lightning network functionality by creating static lightning addreses (LNURL-pay & static internet identifiers) and QR codes which allow you to pull funds from them (LNURL-withdraw)
This SDK supports:
- LNURL-pay (LUD-6, LUD-9, LUD-10, LUD-12)
- LNURL-withdraw (LUD-3)
- Static internet identifiers (LUD-16)
Lightning invoices:
- One time use only
- Need to have a fixed amount, therefore recipient has to set the amount
- Static and bounded expiration
- You can only pay to a lightning invoice, not withdraw funds from it
LNURLs & lightning identifiers:
- Reusable
- Programmable expiry
- Allows payer to set an amount
- Supports both, paying (LNURL-pay) and withdrawing (LNURL-withdraw)
- Possibility to attach a message/comment to a payment
- Receive a message/url as a result of the payment
It is good practice to automatically distinguish between lightning network invoices & LNURLs and adjust the UI accordingly. Therefore there are a few helper functions to help with that:
const isLNInvoice: boolean = swapper.isValidLightningInvoice(_input); //Checks if the input is lightning network invoice
const isLNURL: boolean = swapper.isValidLNURL(_input); //Checks if the input is LNURL or lightning identifier
if(isLNURL) {
//Get the type of the LNURL
const result: (LNURLPay | LNURLWithdraw | null) = await swapper.getLNURLTypeAndData(_input);
if(result.type==="pay") {
const lnurlPayData: LNURLPay = result;
const minPayable: BN = lnurlPayData.min; //Minimum payment amount in satoshis
const maxPayable: BN = lnurlPayData.max; //Maximum payment amount in satoshis
const icon: (string | null) = lnurlPayData.icon; //URL encoded icon that should be displayed on the UI
const shortDescription: (string | null) = lnurlPayData.shortDescription; //Short description of the payment
const longDescription: (string | null) = lnurlPayData.longDescription; //Long description of the payment
const maxCommentLength: (number | 0) = lnurlPayData.commentMaxLength; //Maximum allowed length of the payment message/comment (0 means no comment allowed)
//Should show a UI displaying the icon, short description, long description, allowing the user to choose an amount he wishes to pay and possibly also a comment
}
if(result.type==="withdraw") {
const lnurlWithdrawData: LNURLWithdraw = result;
const minWithdrawable: BN = lnurlWithdrawData.min;
const maxWithdrawable: BN = lnurlWithdrawData.max;
//Should show a UI allowing the user to choose an amount he wishes to withdraw
}
}
const _lnurlOrIdentifier: string = "lnurl1dp68gurn8ghj7ampd3kx2ar0veekzar0wd5xjtnrdakj7tnhv4kxctttdehhwm30d3h82unvwqhkx6rfvdjx2ctvxyesuk0a27"; //Destination LNURL-pay or readable identifier
const _exactIn = false; //exactIn = false, so we specify the output amount
const _amount: BN = new BN(10000); //Amount of satoshis to send (1 BTC = 100 000 000 satoshis)
//Create the swap: swapping SOL to Bitcoin lightning
const swap = await solanaSwapper.create(
Tokens.SOLANA.SOL,
Tokens.BITCOIN.BTCLN,
_amount,
_exactIn,
_lnurlOrIdentifier
);
//Get the amount required to pay and fee
const amountToBePaid: string = swap.getInput().amount; //Human readable amount to be paid on the Solana side (including fee)
const fee: string = swap.getFee().amountInSrcToken.amount; //Human readable swap fee paid on the Solana side (already included in the the above amount)
//Get swap expiration time
const expiry: number = swap.getExpiry(); //Expiration time of the swap in UNIX milliseconds, swap needs to be initiated before this time
//Initiate and pay for the swap
await swap.commit();
//Wait for the swap to conclude
const result: boolean = await swap.waitForPayment();
if(!result) {
//Swap failed, money can be refunded
await swap.refund();
} else {
//Swap successful, we can get the lightning payment secret pre-image, which acts as a proof of payment
const lightningSecret = swap.getSecret();
//In case the LNURL contained a success action, we can read it now and display it to user
if(swap.hasSuccessAction()) {
//Contains a success action that should displayed to the user
const successMessage = swap.getSuccessAction();
const description: string = successMessage.description; //Description of the message
const text: (string | null) = successMessage.text; //Main text of the message
const url: (string | null) = successMessage.url; //URL link which should be displayed
}
}
const _lnurl: string = "lnurl1dp68gurn8ghj7ampd3kx2ar0veekzar0wd5xjtnrdakj7tnhv4kxctttdehhwm30d3h82unvwqhkx6rfvdjx2ctvxyesuk0a27"; //Destination LNURL-pay or readable identifier
const _exactIn = true; //exactIn = true, so we specify the input amount
const _amount = new BN(10000); //Amount in BTC base units - sats
//Create the swap: swapping _amount of satoshis from Bitcoin lightning network to SOL
const swap = await solanaSwapper.create(
Tokens.BITCOIN.BTCLN,
Tokens.SOLANA.SOL,
_amount,
_exactIn,
_lnurl
);
//Get the amount of BTC to be withdrawn from LNURL, amount to be received and fee
const amountToBeWithdrawnOnBitcoin: string = swap.getInput().amount; //Human readable amount of BTC that will be withdrawn from the LNURL
const amountToBeReceivedOnSolana: string = swap.getOutput().amount; //Human readable amount SOL that will be received on Solana
const fee: string = swap.getFee().amountInSrcToken.amount; //Human readable fee in BTC
try {
//Submit the withdraw request & wait for the payment to arrive
await swap.waitForPayment();
//Claim the swap funds - this will initiate 2 Solana transactions
await swap.commitAndClaim();
} catch(e) {
//Error occurred while waiting for payment
}
You can refund the swaps in one of two cases:
- In case intermediary is non-cooperative and goes offline, you can claim the funds from the swap contract back after some time.
- In case intermediary tried to pay but was unsuccessful, so he sent you signed message with which you can refund now without waiting.
This call can be checked on every startup and periodically every few minutes.
//Get the swaps
const refundableSwaps = await swapper.getRefundableSwaps();
//Refund all the swaps
for(let swap of refundableSwaps) {
await swap.refund();
}
Returns swaps that are ready to be claimed by the client, this can happen if client closes the application when a swap is in-progress and the swap is concluded while the client is offline.
//Get the swaps
const claimableSwaps = await swapper.getClaimableSwaps();
//Claim all the claimable swaps
for(let swap of claimableSwaps) {
await swap.commitAndClaim();
}