Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add min fee to frontend #20

Open
wants to merge 246 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
246 commits
Select commit Hold shift + click to select a range
32524ae
setup codebase
MagicDev090 Apr 28, 2023
d8c6d69
fixed header style
MagicDev090 May 2, 2023
34ad13a
updated backend
MagicDev090 May 2, 2023
1eeb61a
reverted background
MagicDev090 May 2, 2023
d77e65d
remove package.json outside
MagicDev090 May 2, 2023
92709c1
fixed eslint errors
MagicDev090 May 2, 2023
4f19189
updated color
MagicDev090 May 2, 2023
5af3669
aligned header center
MagicDev090 May 2, 2023
d5741d4
added box shadow to button
MagicDev090 May 2, 2023
e35fb7f
fixed header style on mobile
MagicDev090 May 4, 2023
cba880e
fixed lint issues
MagicDev090 May 4, 2023
2919dc0
fixed header style issue on mobile mode
MagicDev090 May 4, 2023
74c13a6
fixed mobile menu font style
MagicDev090 May 4, 2023
cf39456
fixed header style issue
MagicDev090 May 4, 2023
82d0234
Merge pull request #1 from ZigZagExchange/update/header
MagicDev090 May 4, 2023
c3100f4
updated swap
MagicDev090 May 8, 2023
f591ce8
fixed yarn lint
MagicDev090 May 8, 2023
899ef07
fixed type errors
MagicDev090 May 8, 2023
f1037fa
added token selector
MagicDev090 May 8, 2023
7ffb9ba
fixed type erros
MagicDev090 May 8, 2023
44223ab
updated swap
MagicDev090 May 9, 2023
5077eda
added max button
MagicDev090 May 9, 2023
3e183bf
switched to bridge
MagicDev090 May 11, 2023
81f4390
updated bridge
MagicDev090 May 12, 2023
97379c1
fixed feedback
MagicDev090 May 14, 2023
0c454d0
Merge pull request #2 from ZigZagExchange/update/swapForm
MagicDev090 May 14, 2023
cf340db
updated tokens
MagicDev090 May 15, 2023
3de2944
removed unnecessary tokens
MagicDev090 May 16, 2023
00d42ac
removed unnecessary tokens in network modal
MagicDev090 May 16, 2023
b414946
Merge pull request #3 from ZigZagExchange/someUpdate
MagicDev090 May 17, 2023
f0e7837
add node module for wagmi
MagicDev090 May 22, 2023
0d548de
draft wallet connect feature
MagicDev090 May 22, 2023
d0068ec
BTCBridge
taureau75 May 23, 2023
2c039a3
deposit currencies
taureau75 May 23, 2023
0440c15
beneficiary ETH transfer
taureau75 May 23, 2023
1404859
payable beneficiary
taureau75 May 23, 2023
da7b154
add out chain and address
taureau75 May 23, 2023
3c273bc
eth get deposits
taureau75 May 23, 2023
a1c2c20
grab last 100 blocks of deposits
taureau75 May 23, 2023
5877f9f
added switch network & swap function
MagicDev090 May 24, 2023
bc97523
added networks & tokens
MagicDev090 May 24, 2023
6e0a2f1
updated networkselector
MagicDev090 May 24, 2023
f67d5c1
updated
MagicDev090 May 24, 2023
5367bc6
removed unnecessary imports
MagicDev090 May 24, 2023
eaf16eb
updated chains
MagicDev090 May 24, 2023
91c4cbb
btc deposit script
taureau75 May 24, 2023
3314d64
updates to btc and eth deposit scripts
taureau75 May 24, 2023
4155bf7
schema updates
taureau75 May 24, 2023
eed6573
functioning deposit address generation
taureau75 May 24, 2023
927ec0e
deposit address schema
taureau75 May 24, 2023
ba459cc
working btc and eth deposits
taureau75 May 24, 2023
ef4a973
functioning btc pay script
taureau75 May 25, 2023
b3431c5
add fees to btc pay
taureau75 May 25, 2023
8fa47f3
removed useless files
MagicDev090 May 25, 2023
cbd3d68
eth payments
taureau75 May 25, 2023
82a38be
update beneficiary
taureau75 May 25, 2023
40d7fdd
fixed wallet & mobile issue
MagicDev090 May 25, 2023
8824379
updated mobile menu items
MagicDev090 May 25, 2023
dd5d192
select active token
MagicDev090 May 26, 2023
7018b11
updated token list
MagicDev090 May 26, 2023
9b087b2
fixed issues on network slider
MagicDev090 May 26, 2023
3f5d841
add phantom wallet
MagicDev090 May 29, 2023
3561c0e
allow different bitcoin-cli prefixes
taureau75 May 31, 2023
7fdf639
update infura project id
taureau75 May 31, 2023
5d428f9
error handling for eth-btc
taureau75 May 31, 2023
b0b03ba
group eth_btc together
taureau75 May 31, 2023
acc5518
update abi path
taureau75 May 31, 2023
15856cc
eth lightning folder
taureau75 May 31, 2023
4e2151d
mainnet to config
taureau75 May 31, 2023
bef0004
mainnet beneficiary
taureau75 May 31, 2023
61b29cc
configurable bitcoin-cli
taureau75 May 31, 2023
22c2ef6
charge less network fee
taureau75 May 31, 2023
931105f
faster confirmations on btc
taureau75 May 31, 2023
8831a14
eth address validation
taureau75 May 31, 2023
4719504
more error handling for bad addresses
taureau75 May 31, 2023
b26c344
update Logic
MagicDev090 Jun 1, 2023
4b7761d
token list with Chain
MagicDev090 Jun 1, 2023
be5fe4b
dropdown
MagicDev090 Jun 1, 2023
ca50cb3
error handling for prices
Jun 1, 2023
e6bd446
bridge history
Jun 1, 2023
1f2cd65
refactor codebase
MagicDev090 Jun 1, 2023
42b0fc2
clean
MagicDev090 Jun 1, 2023
5584514
remove files
MagicDev090 Jun 1, 2023
fccb08c
fix error
MagicDev090 Jun 1, 2023
53206d4
fetch balance
MagicDev090 Jun 2, 2023
6fdc69d
update balance
MagicDev090 Jun 4, 2023
9423bb2
add loader
MagicDev090 Jun 4, 2023
49234f0
remove toast
MagicDev090 Jun 5, 2023
277ce96
disconnect
MagicDev090 Jun 5, 2023
7fe2c5c
auto connect
MagicDev090 Jun 5, 2023
cf1e50a
Merge pull request #4 from ZigZagExchange/feature/wallet-connect
MagicDev090 Jun 5, 2023
691a4ab
add ETH/SOL bridge
Jun 5, 2023
7dd6a06
add docs
Jun 5, 2023
a8224db
Merge pull request #5 from penemue698/master
taureau75 Jun 5, 2023
3377b74
Revert "add ETH-SOL bridge"
taureau75 Jun 5, 2023
29165f2
Merge pull request #6 from ZigZagExchange/revert-5-master
taureau75 Jun 5, 2023
b4e1b37
add BTC
MagicDev090 Jun 6, 2023
6efc7c2
deposits table for scalability
penemue698 Jun 6, 2023
63256a2
Merge remote-tracking branch 'upstream/master'
penemue698 Jun 6, 2023
0bab08a
Merge pull request #7 from penemue698/master
taureau75 Jun 7, 2023
b29d410
make postgres DB configurable
taureau75 Jun 7, 2023
606beb8
better errors
defibuildereth Jun 7, 2023
9908f3f
change btc_deposit endpoint name
taureau75 Jun 7, 2023
988b47d
add solana web3 dependency
taureau75 Jun 7, 2023
44e0661
rename deposits table to sol_deposits
penemue698 Jun 7, 2023
f2defb3
Merge pull request #8 from penemue698/master
taureau75 Jun 7, 2023
174d9fa
quick bug fixes
Jun 7, 2023
e7f684f
add solana web3 dependency
Jun 7, 2023
3821627
metamask pops
defibuildereth Jun 8, 2023
2ad27cd
form
defibuildereth Jun 8, 2023
21faa9e
sent eth-btc bridge through frontend
defibuildereth Jun 8, 2023
f9a211e
hooked up to basic form
defibuildereth Jun 8, 2023
567d3b2
wallet
MagicDev090 Jun 8, 2023
09c8272
eliminate race conditions on payments
Jun 8, 2023
50c2251
Merge pull request #9 from ZigZagExchange/btc-lightning
MagicDev090 Jun 8, 2023
3231323
Merge branch 'dev' into sendTx
defibuildereth Jun 8, 2023
9d4d23f
custom debounce function (dependancy conflict)
defibuildereth Jun 8, 2023
ee055bb
prices api
penemue698 Jun 8, 2023
a61a434
Merge remote-tracking branch 'upstream/master'
penemue698 Jun 8, 2023
540dd73
Merge pull request #10 from penemue698/master
taureau75 Jun 8, 2023
42ec722
added modal
defibuildereth Jun 8, 2023
dbf417b
add modal to form
defibuildereth Jun 8, 2023
14012dc
API Documentation
SMAXGUY Jun 8, 2023
06552fd
Merge pull request #11 from penemue698/API-Documentation
taureau75 Jun 8, 2023
dfb5a05
Update README.md
taureau75 Jun 8, 2023
ae7a8aa
Update README.md
taureau75 Jun 8, 2023
e476aee
Update README.md
taureau75 Jun 8, 2023
7e84ece
Update README.md
taureau75 Jun 9, 2023
89ff8d9
move README to root
taureau75 Jun 9, 2023
2486648
Update README.md
taureau75 Jun 9, 2023
4cfe5fc
Update README.md
taureau75 Jun 9, 2023
ed2eb9e
add fetch history to api
defibuildereth Jun 9, 2023
a7b399a
displaying BridgeHistory info
defibuildereth Jun 9, 2023
4fe6958
history table
defibuildereth Jun 9, 2023
f3a55c9
history table accepts address parameter
defibuildereth Jun 9, 2023
ad4d0c1
table formatting, tx send and mined updates working
defibuildereth Jun 9, 2023
31773bd
Merge branch 'dev' of github.com:ZigZagExchange/lightning-dex
taureau75 Jun 9, 2023
1bc1d40
price sanity checks
penemue698 Jun 9, 2023
abf9219
eth-sol beneficiary
taureau75 Jun 9, 2023
138cf90
Update README.md
taureau75 Jun 9, 2023
857dfec
major bug fix to sol_pay
Jun 9, 2023
67165d5
poll api for bridge tx, pull hashes through to modal
defibuildereth Jun 9, 2023
704a40b
missed file
defibuildereth Jun 9, 2023
a0a13d0
Merge pull request #12 from penemue698/master
taureau75 Jun 10, 2023
2dc06f7
Merge pull request #13 from defibuildereth/sendTx
taureau75 Jun 10, 2023
19eb057
lint fixes
taureau75 Jun 10, 2023
b112a09
Merge branch 'master' of github.com:ZigZagExchange/lightning-dex into…
taureau75 Jun 10, 2023
01a6339
include bug fix
taureau75 Jun 10, 2023
9dd4438
disable lightning and arbitrum
taureau75 Jun 10, 2023
f1a7b43
border changes to withdraw field
taureau75 Jun 10, 2023
78ee231
styling and layout fixes
taureau75 Jun 10, 2023
356fe08
get rid of some extra stuff
taureau75 Jun 10, 2023
6c80ffb
get rid of contracts and portfolio
taureau75 Jun 10, 2023
257b929
prices
taureau75 Jun 10, 2023
049a3dc
hide settings
taureau75 Jun 10, 2023
6f4dec9
update bridge amounts
taureau75 Jun 11, 2023
de05fc8
fix eth reconnection issue
taureau75 Jun 11, 2023
318e20c
lint fix
taureau75 Jun 11, 2023
e2d24ff
lots of build fixes
taureau75 Jun 11, 2023
386a70f
build fixed
taureau75 Jun 11, 2023
d07e8fd
fix weird initial value for amounts
taureau75 Jun 11, 2023
594b37a
minimize more
taureau75 Jun 11, 2023
e4d98fc
working eth -> btc
taureau75 Jun 12, 2023
1789472
eth -> sol and btc deposit address
taureau75 Jun 12, 2023
527231f
make text visible
taureau75 Jun 12, 2023
910d20a
swapping amounts
taureau75 Jun 12, 2023
b36ff95
lint fixes
taureau75 Jun 12, 2023
338504d
build
taureau75 Jun 12, 2023
3305b11
unsupported chains
taureau75 Jun 12, 2023
c37ae95
solana mainnet rpc
taureau75 Jun 12, 2023
29db68e
bug fix sol pay
Jun 13, 2023
73608f0
merge
Jun 13, 2023
90b9f64
working sol payments
taureau75 Jun 13, 2023
2e36b22
lint fixes
taureau75 Jun 13, 2023
a275234
build fixes
taureau75 Jun 13, 2023
9b606f1
Merge branch 'master' of github.com:ZigZagExchange/lightning-dex
taureau75 Jun 13, 2023
d54f302
bug fix for solana wallet
taureau75 Jun 13, 2023
5895b00
SOL Address and wallet connect validation
taureau75 Jun 13, 2023
9cea7eb
lint fix
taureau75 Jun 13, 2023
1c50547
clear amounts on swapChain
taureau75 Jun 13, 2023
b186a58
bitcoin address validation
taureau75 Jun 13, 2023
1194afe
lint fix
taureau75 Jun 13, 2023
9bd5de2
set default dest chain bitcoin
taureau75 Jun 13, 2023
4e8e1e3
lint fix
taureau75 Jun 13, 2023
8c7770e
remove logging
taureau75 Jun 13, 2023
4246550
try catch sol deposits
Jun 13, 2023
bb1ce39
Merge branch 'master' of github.com:ZigZagExchange/lightning-dex
Jun 13, 2023
0d5d03a
try-catch sol errors
taureau75 Jun 13, 2023
7196648
Merge branch 'master' of github.com:ZigZagExchange/lightning-dex
taureau75 Jun 13, 2023
c7e5c08
lint fix
taureau75 Jun 13, 2023
4f4bd8c
ugly history and transaction tracking
taureau75 Jun 13, 2023
350d920
build fixes
taureau75 Jun 13, 2023
6d33f7d
reduce transaction waiting period to 4
taureau75 Jun 13, 2023
c124b68
update solana logo
taureau75 Jun 13, 2023
3977579
history subtext
taureau75 Jun 13, 2023
e82a647
cute price display
taureau75 Jun 13, 2023
678315a
disable toggle currency screen
taureau75 Jun 14, 2023
9f5f704
remove carats
taureau75 Jun 14, 2023
8c44876
try and figure out solana issue
taureau75 Jun 14, 2023
fb4e924
bug fix for phantom freeze
taureau75 Jun 14, 2023
20e1898
network fee & dollar prices
taureau75 Jun 14, 2023
a391da6
prevent negative outputs
taureau75 Jun 14, 2023
88938d4
bug fix
taureau75 Jun 14, 2023
310216c
catch failure in API
taureau75 Jun 14, 2023
67c81ea
set paid to true when sending money out
taureau75 Jun 14, 2023
b3560e7
try to avoid double payment
taureau75 Jun 14, 2023
b543300
dont fetch prices if unnecessary
Jun 14, 2023
7b7f362
more sol pay fixes
taureau75 Jun 14, 2023
aa5d7b5
race condition check for eth double payment
taureau75 Jun 14, 2023
18a0709
race condition btc failure
taureau75 Jun 14, 2023
457338f
maintenance
taureau75 Jun 14, 2023
1fbdce8
major bug fix bitcoin
Jun 14, 2023
397304d
Merge branch 'master' of github.com:ZigZagExchange/lightning-dex
Jun 14, 2023
ca677d6
bug fix
taureau75 Jun 14, 2023
e1072e1
bug fix
Jun 14, 2023
b92d99c
restart bridge
taureau75 Jun 14, 2023
ae1fc6f
Merge branch 'master' of github.com:ZigZagExchange/lightning-dex
taureau75 Jun 14, 2023
8e31159
change order of operations for sol deposit
penemue698 Jun 15, 2023
2a1d7c2
Merge pull request #15 from ZigZagExchange/fix-sol-deposit-race-condi…
taureau75 Jun 15, 2023
6d4be06
0.1% fee for eth-btc
taureau75 Jun 15, 2023
86de788
Merge branch 'master' of github.com:ZigZagExchange/lightning-dex
taureau75 Jun 15, 2023
aa3b990
change eth-sol fees to 0.1%
taureau75 Jun 15, 2023
2838d1a
increase eth-btc size
taureau75 Jun 16, 2023
3ba2d43
increase eth-btc size
taureau75 Jun 16, 2023
a0723c7
alerts for bridge errors
penemue698 Jun 16, 2023
ecfad5b
Merge pull request #16 from ZigZagExchange/error-notifications
taureau75 Jun 16, 2023
8b8cc67
hide logs for failed axios
taureau75 Jun 16, 2023
5316ef9
bug fix
Jun 16, 2023
dfa04b2
increase max sizes
taureau75 Jun 16, 2023
e99803c
Merge branch 'master' of github.com:ZigZagExchange/lightning-dex
taureau75 Jun 16, 2023
32a6421
eth deposit less logging
taureau75 Jun 16, 2023
9e19f8a
add available liquidity endpoint
penemue698 Jun 16, 2023
b159cd7
missing return
penemue698 Jun 16, 2023
c9a0a6d
Merge pull request #17 from ZigZagExchange/available-liquidity-endpoint
taureau75 Jun 16, 2023
c0e06d7
2 eth pools
taureau75 Jun 16, 2023
3e85b44
performance improvement for liquidity
taureau75 Jun 16, 2023
fac9c85
max liquidity
taureau75 Jun 16, 2023
86519ab
regular liquidity refresh, limit history + price refresh rate
taureau75 Jun 17, 2023
4d21c31
interval for prices
taureau75 Jun 17, 2023
3fa38b7
build fixes
taureau75 Jun 17, 2023
8c3bd59
fix refetch intervals
penemue698 Jun 17, 2023
486069b
Merge pull request #18 from ZigZagExchange/fix-refetch-intervals
taureau75 Jun 17, 2023
08dc458
grab prices immediately
taureau75 Jun 17, 2023
261fc84
1 dollar min fee
penemue698 Jun 18, 2023
449571e
Merge pull request #19 from ZigZagExchange/1-dollar-min-fee
taureau75 Jun 18, 2023
7f5f940
add min fee to frontend
penemue698 Jun 20, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
150 changes: 139 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,25 +1,153 @@
# Lightning DEX
# Zap

The smart contract is currently deployed to Arbitrum at the address:
Zap is a cross-chain crypto swap protocol. It specializes in supporting native tokens with no counterparty risk such as ETH, BTC, and SOL.

This document provides an overview of how to interact with the protocol.

## Base URLs

* Mainnet: https://api.zap.zigzag.exchange
* Testnet: https://api.zap.zigzag.exchange/testnet

## Currencies

The following currencies are supported by the API:

* BTC: Bitcoin
* ETH: Ethereum
* SOL: Solana

## Swaps

The following swaps are supported by the API:

* ETH-SOL
* ETH-BTC

## Pricing

There is an endpoint `GET /prices` that you can use to see the price the protocol is offering. The prices are determined by the average of the top 3 exchanges by volume for a given currency.

All swaps are conducted at market price when the depositing transaction hits finality. Finality is determined as follows for the following chains.

* ETH: 3 confirmations (~45 seconds)
* BTC: 1 confirmation (~10 minutes)
* SOL: 1 confirmation (~5 seconds)

There is a possibility, especially on BTC, that the market price moves significantly between when you send the transaction and when the transaction finalizes. This is the risk you choose to take when you interact with the protocol.

# Fees

A variable network fee, plus a 0.2% trading fee, is charged on each swap.

The network fees are calculated as follows:

SOL: essentially 0
ETH: (Current base fee for a simple ETH transfer) * 2
BTC: (1-block confirmation fee-rate) * (400 vB)

## Testnets

We use the Goerli Testnet for ETH, Solana Devnet for SOL, and Bitcoin Testnet for BTC.

Your funds can be irrevecably lost if you use the mainnet improperly. Please verify your code on testnet before implementing it on mainnet.

## Smart Contracts

Swapping from ETH to SOL or BTC is done via a smart contract. The verified code and ABI for each contract is available on Etherscan.

To send ETH, call the `depositETH` function on the appropriate contract with the requested ETH `value`, `out_chain`, and `out_address`. The `out_chain` must be `SOL` on the ETH-SOL contract and `BTC` on the ETH-BTC contract.

* ETH-BTC (mainnet): [0x64Ca3FCa3B43c98F12A9E9509f9cF8AB18abc208](https://etherscan.io/address/0x64Ca3FCa3B43c98F12A9E9509f9cF8AB18abc208)
* ETH-SOL (mainnet): [0xd484ed3cdF6f34d9Cca869240107E1E8a03BaE96](https://etherscan.io/address/0xd484ed3cdF6f34d9Cca869240107E1E8a03BaE96)

The contracts are avaiable on Goerli Testnet for testing as well.

* ETH-BTC (testnet): [0xC7F355DE8cC7ec65d275f6Bc3349787c9FB48ACD](https://goerli.etherscan.io/address/0xC7F355DE8cC7ec65d275f6Bc3349787c9FB48ACD)
* ETH-SOL (testnet): [0x43b2FF69196a1b9641C1fCBaB6A869B4e256Fb12](https://goerli.etherscan.io/address/0x43b2FF69196a1b9641C1fCBaB6A869B4e256Fb12)

## Deposit Addresses

Swapping from BTC or SOL to ETH is supported via deposit addresses. Please see the endpoints for more detail.

## Endpoints

### GET /btc_deposit

Generate a deposit address to swap BTC for ETH. Every outgoing address will have a unique deposit address. Make sure you double check the address you enter. If you enter the wrong `outgoing_address` your ETH will be lost forever and we will not refund you.

Example Request:

https://api.zap.zigzag.exchange/btc_deposit?outgoing_currency=ETH&outgoing_address=0xE4ADed7c6515c73B83f6aC4C01930c8A40A1c43E

Response:

```
{
"deposit_currency":"BTC",
"deposit_address":"tb1qjylf9cscuj89gucm7tkackx4qsxh7ungsmzuxq",
"outgoing_currency":"ETH",
"outgoing_address":"0xE4ADed7c6515c73B83f6aC4C01930c8A40A1c43E"
}
```
0x7F6678cdBC715F15501342ecFB34ABCC903cBF6F

### GET /sol_deposit

Generate a deposit address to swap SOL for ETH. SOL deposit addresses are one time use and expire at the specified time. Duplicate deposits or deposits sent after the expiry will not be processed.

Example Request:

https://api.zap.zigzag.exchange/sol_deposit?outgoing_currency=ETH&outgoing_address=0xE4ADed7c6515c73B83f6aC4C01930c8A40A1c43E

Response:

```
{
"deposit_address":"F5E9kwLLPQ2P4RAeQLGGSrDrbVuaSsaXHcXSDCHiWFn8",
"expires_at":1686263061
}
```



You can view it on Arbiscan: https://arbiscan.io/address/0x7F6678cdBC715F15501342ecFB34ABCC903cBF6F
### GET /history/:address

The backend is deployed to https://api.bitcoin.zigzag.exchange
Get an account's bridging history.

The frontend is currently deployed to https://lightning-dex.vercel.app/ but should be used with great caution.
Example Request:

We have a public Lightning node. You can connect to us at:
https://api.zap.zigzag.exchange/history/0xE4ADed7c6515c73B83f6aC4C01930c8A40A1c43E

Response:

Mainnet:
```
02572fcd9ca25472108ff62b975dff47f5625e57abcf0f354065c9586db8dbd632@34.214.120.115:9735
[
{
"deposit_currency": "BTC",
"deposit_address": "bc1qdknckpa5h5kl2wedhsjw6n85ddkytf9dmfrz2u",
"deposit_amount": "0.01",
"deposit_txid": "0cd7c085eda7431c6d634afed0c681cb2bf2fa998ac9a2b3137172e37ed272d8",
"deposit_timestamp": "2023-06-01T19:40:33.786Z",
"outgoing_currency": "ETH",
"outgoing_address": "0xE4ADed7c6515c73B83f6aC4C01930c8A40A1c43E",
"outgoing_amount": "0.1405146142799961",
"outgoing_txid": "0x670b46ec75934ea2bfb3d98d3ea1b0038ded6447604a2dd891517ad83e3f865a",
"outgoing_timestamp": "2023-06-01T19:40:49.590Z",
"paid": true
}
]
```
### GET /prices

Example Request:

https://api.zap.zigzag.exchange/prices

Testnet:
Response
```
03289786c1fd9c2ddb4936186958636a2d2cbf9ef2fdd43a342ad72377711ae326@34.214.120.115:19735
{
"btc_usd": 26690.19,
"eth_usd": 1853.5622852385998,
"sol_usd": 18.873888749272282
}
```
183 changes: 132 additions & 51 deletions backend/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,32 @@ const { Pool } = require('pg');
const crypto = require('crypto');
const nodeChildProcess = require('node:child_process');
const util = require('node:util');
const dotenv = require('dotenv');
const { ethers } = require('ethers');
const solana = require('@solana/web3.js')
const {v4: uuid} = require('uuid')
const axios = require('axios')
const bs58 = require('bs58')
const BigNumber = require('bignumber.js')

const exec = util.promisify(nodeChildProcess.exec);
dotenv.config();

const db = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: { rejectUnauthorized: false },
})
const solanaConnection = new solana.Connection(process.env.SOLANA_CONNECTION_URL)
const ethersProvider = new ethers.InfuraProvider(
process.env.ETH_NETWORK,
process.env.INFURA_PROJECT_ID,
);

async function runDbMigration () {
await db.query(`
CREATE TABLE IF NOT EXISTS hashes (
hash TEXT PRIMARY KEY,
invoice TEXT
)
`);
await db.query(`
CREATE TABLE IF NOT EXISTS invoice_requests (
id SERIAL PRIMARY KEY,
amount NUMERIC
)
`);
}

runDbMigration();
const exec = util.promisify(nodeChildProcess.exec);

const db = new Pool({
host: 'localhost',
port: 5432,
database: process.env.POSTGRES_DB,
user: 'postgres',
password: 'postgres'
});

// CORS
app.use('/', (req, res, next) => {
Expand All @@ -43,48 +45,127 @@ app.use('/', (req, res, next) => {

app.use(express.json());

app.post('/invoice', async (req, res, next) => {
const invoice = req.body.invoice;
let decodedInvoice;
try {
decodedInvoice = LNInvoice.decode(invoice);
} catch (e) {
return next("Bad invoice: " + e.message);
}
const now = Math.floor(Date.now() / 1000)
const unix_expiry = decodedInvoice.timestamp + decodedInvoice.expiry;
if (unix_expiry < now + 600) {
return next("Bad expiry. Expires in less than 10 min");
app.get('/btc_deposit', async (req, res, next) => {
const outgoing_currency = req.query.outgoing_currency;
const outgoing_address = req.query.outgoing_address;

const valid_outgoing_currencies = ["ETH"];
if (!valid_outgoing_currencies.includes(outgoing_currency)) return next("Bad outgoing_currency")
if (!outgoing_address) return next("Must set outgoing_address")
if (!ethers.isAddress(outgoing_address)) return next("Invalid outgoing_address")

const deposit_address = await db.query("SELECT * FROM deposit_addresses WHERE deposit_currency=$1 AND outgoing_currency=$2 AND outgoing_address=$3 LIMIT 1", ["BTC", outgoing_currency, outgoing_address]);

if (deposit_address.rows.length > 0) return res.status(200).json(deposit_address.rows[0]);
else {
const addressgen = await exec(`${process.env.BITCOIN_CLI_PREFIX} getnewaddress`);
const deposit_address = addressgen.stdout.trim();
try {
await db.query("INSERT INTO deposit_addresses (deposit_currency, deposit_address, outgoing_currency, outgoing_address) VALUES ($1,$2,$3,$4)", ["BTC", deposit_address, outgoing_currency, outgoing_address]);
} catch (e) {
return next(e);
}
return res.status(200).json({ deposit_address, outgoing_currency, outgoing_address });
}
const hash = decodedInvoice.paymentHash.toString('hex');
});

app.get("/history/:address", async (req, res, next) => {
if (!req.params.address) return next("GET /history/:address. Missing address");
try {
const bridges = await db.query("SELECT * FROM bridges WHERE LOWER(deposit_address)=$1 OR LOWER(outgoing_address)=$1", [req.params.address.toLowerCase()]);
return res.status(200).json(bridges.rows);
} catch (e) {
return next(e);
}
});

function deriveSolanaDepositAddress (depositId) {
const masterPrivateKey = Buffer.from(process.env.SOL_LIQUIDITY_ACCOUNT_PRIV_KEY_BASE58, 'utf-8')
const seed = crypto.createHash('sha256').update(masterPrivateKey).update(depositId).digest()
return solana.Keypair.fromSeed(seed).publicKey.toString()
}

const SOL_DEPOSIT_EXPIRY_PERIOD = 3600 // 1 hour

app.get('/sol_deposit', async (req, res, next) => {
const outgoingCurrency = req.query.outgoing_currency
const outgoingAddress = req.query.outgoing_address

if (outgoingCurrency !== 'ETH') return next('Only eth bridges supported')
if (!ethers.isAddress(outgoingAddress)) return next("Invalid outgoing_address")

const depositId = uuid()
const depositAddress = deriveSolanaDepositAddress(depositId)
const expiry = Math.floor(new Date().getTime() / 1000) + SOL_DEPOSIT_EXPIRY_PERIOD
await db.query('INSERT INTO sol_deposits (id, deposit_address, outgoing_currency, outgoing_address, expiry) VALUES ($1,$2,$3,$4,to_timestamp($5))', [depositId, depositAddress, outgoingCurrency, outgoingAddress, expiry])
return res.status(200).json({
deposit_address: depositAddress,
expires_at: expiry
})
})

app.get('/prices', async (_, res) => {
let gmxPrices;
let coinCapPrices;
try {
await db.query("INSERT INTO hashes VALUES ($1, $2)", [hash, invoice]);
}
catch (e) {
return next(e.detail);
gmxPrices = await axios.get('https://api.gmx.io/prices').then(({ data })=> ({
btc_usd: data['0x2f2a2543B76A4166549F7aaB2e75Bef0aefC5B0f'] / 1e30,
eth_usd: data['0x82aF49447D8a07e3bd95BD0d56f35241523fBab1'] / 1e30
}))
coinCapPrices = await axios.get('https://api.coincap.io/v2/assets', {
headers: {
'Authorization': `Bearer ${process.env.COIN_CAP_API_KEY}`
}
}).then(({data}) => ({
sol_usd: Number(data.data.find(asset => asset.id === 'solana').priceUsd)
}))
} catch (e) {
return next("Failed to get prices");
}
res.status(200).json({"success": true });

return res.status(200).json({
...gmxPrices,
...coinCapPrices
})
})

app.get('/hash/:hash', async (req, res, next) => {
const hashes = await db.query("SELECT * FROM hashes WHERE hash=$1", [req.params.hash]);
if (hashes.rows.length > 0) res.status(200).json(hashes.rows[0]);
else next("Hash not found");
app.get('/available_liquidity', async (_, res) => {
const balances = await Promise.all([
getSolanaBalance(),
getEthereumBalance(process.env.ETH_SOL_LIQUIDITY_ADDRESS),
getEthereumBalance(process.env.ETH_BTC_LIQUIDITY_ADDRESS),
getBitcoinBalace()
]);

return res.status(200).json({
sol: balances[0],
eth_sol: balances[1],
eth_btc: balances[2],
btc: balances[3],
})
})

app.get('/invoice/request/:amount', async (req, res, next) => {
const amount = parseInt(req.params.amount);
if (isNaN(amount)) return next("Invalid amount");
if (amount < 2000) return next("Min amount is 2000");
const invoicegen = await exec(`lncli addinvoice --amt ${amount}`);
const invoice = JSON.parse(invoicegen.stdout)
async function getSolanaBalance () {
const decoded = bs58.decode(process.env.SOL_LIQUIDITY_ACCOUNT_PRIV_KEY_BASE58)
const liqudityKeyPair = solana.Keypair.fromSecretKey(decoded)
const solanaBalance = await solanaConnection.getBalance(liqudityKeyPair.publicKey)
return solanaBalance / solana.LAMPORTS_PER_SOL
}

async function getEthereumBalance (address) {
const balance = await ethersProvider.getBalance(address);
return new BigNumber(balance.toString()).div(1e18).toNumber()
}

res.status(200).json(invoice);
});
async function getBitcoinBalace () {
const balanceCheck = await exec(`${process.env.BITCOIN_CLI_PREFIX} getwalletinfo`);
const walletInfo = JSON.parse(balanceCheck.stdout);
return walletInfo.balance
}

app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ err })
})

module.exports = { app, db, runDbMigration }
module.exports = { app, db }
Loading