-
Notifications
You must be signed in to change notification settings - Fork 1
/
deposit_ethereum.go
473 lines (391 loc) · 12.6 KB
/
deposit_ethereum.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
package client
import (
"bytes"
"context"
"encoding/json"
"fmt"
"math/big"
"net/http"
"strconv"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/tanx-libs/tanx-connector-go/contract"
)
type CoinStatusPayload struct {
Symbol Currency `json:"symbol"`
Quanitization string `json:"quanitization"`
Decimal string `json:"decimal"`
BlockchainDecimal string `json:"blockchain_decimal"`
TokenContract string `json:"token_contract"`
StarkAssetID string `json:"stark_asset_id"`
}
type CoinStatusResponse struct {
Status Status `json:"status"`
Message string `json:"message"`
Payload map[string]CoinStatusPayload `json:"payload"`
}
func (c *Client) getCoinStatus(ctx context.Context) (CoinStatusResponse, error) {
err := c.CheckAuth()
if err != nil {
return CoinStatusResponse{}, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.coinURL.String(), nil)
if err != nil {
return CoinStatusResponse{}, err
}
resp, err := c.httpClient.Do(req)
if err != nil {
return CoinStatusResponse{}, err
}
defer resp.Body.Close()
var coinStatusResponse CoinStatusResponse
err = json.NewDecoder(resp.Body).Decode(&coinStatusResponse)
if coinStatusResponse.Status == ERROR {
if resp.StatusCode >= 400 && resp.StatusCode < 500 {
return CoinStatusResponse{}, &ErrClient{
Status: resp.StatusCode,
Err: fmt.Errorf(coinStatusResponse.Message),
}
} else if resp.StatusCode >= 500 {
return CoinStatusResponse{}, &ErrServer{
Status: resp.StatusCode,
Err: fmt.Errorf(coinStatusResponse.Message),
}
}
return CoinStatusResponse{}, fmt.Errorf("status: %d\nerror: %s", resp.StatusCode, coinStatusResponse.Message)
} else if err != nil {
return CoinStatusResponse{}, &ErrJSONDecoding{Err: err}
}
return coinStatusResponse, nil
}
type VaultResponse struct {
Status Status `json:"status"`
Message string `json:"message"`
Payload struct {
ID int `json:"id"`
Coin string `json:"coin"`
} `json:"payload"`
}
type VaultRequest struct {
Coin Currency `json:"coin"`
}
func (c *Client) getVaultID(ctx context.Context, currency Currency) (int, error) {
err := c.CheckAuth()
if err != nil {
return 0, nil
}
r := VaultRequest{
Coin: currency,
}
requestBody, err := json.Marshal(r)
if err != nil {
return 0, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.vaultIDURL.String(), bytes.NewReader(requestBody))
if err != nil {
return 0, err
}
req.Header.Set("Authorization", fmt.Sprintf("JWT %s", c.jwtToken))
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
var vaultResponse VaultResponse
err = json.NewDecoder(resp.Body).Decode(&vaultResponse)
if vaultResponse.Status == ERROR {
if resp.StatusCode >= 400 && resp.StatusCode < 500 {
return 0, &ErrClient{
Status: resp.StatusCode,
Err: fmt.Errorf(vaultResponse.Message),
}
} else if resp.StatusCode >= 500 {
return 0, &ErrServer{
Status: resp.StatusCode,
Err: fmt.Errorf(vaultResponse.Message),
}
}
return 0, fmt.Errorf("status: %d\nerror: %s", resp.StatusCode, vaultResponse.Message)
} else if err != nil {
return 0, &ErrJSONDecoding{Err: err}
}
return vaultResponse.Payload.ID, nil
}
type CryptoDepositRequest struct {
Amount string `json:"amount"`
StarkAssetID string `json:"token_id"`
StarkPublicKey string `json:"stark_key"`
DepositBlockchainHash string `json:"deposit_blockchain_hash"`
DepositBlockchainNonce string `json:"deposit_blockchain_nonce"`
VaultID int `json:"vault_id"`
}
type CryptoDepositResponse struct {
Status Status `json:"status"`
Message string `json:"message"`
Payload interface{} `json:"payload"`
}
func (c *Client) cryptoDepositStart(ctx context.Context, depositReq CryptoDepositRequest) (CryptoDepositResponse, error) {
err := c.CheckAuth()
if err != nil {
return CryptoDepositResponse{}, err
}
requestBody, err := json.Marshal(depositReq)
if err != nil {
return CryptoDepositResponse{}, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.cryptoDepositStartURL.String(), bytes.NewReader(requestBody))
if err != nil {
return CryptoDepositResponse{}, err
}
req.Header.Set("Authorization", fmt.Sprintf("JWT %s", c.jwtToken))
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return CryptoDepositResponse{}, err
}
defer resp.Body.Close()
var cryptoDepositResponse CryptoDepositResponse
err = json.NewDecoder(resp.Body).Decode(&cryptoDepositResponse)
if cryptoDepositResponse.Status == ERROR {
if resp.StatusCode >= 400 && resp.StatusCode < 500 {
return CryptoDepositResponse{}, &ErrClient{
Status: resp.StatusCode,
Err: fmt.Errorf(cryptoDepositResponse.Message),
}
} else if resp.StatusCode >= 500 {
return CryptoDepositResponse{}, &ErrServer{
Status: resp.StatusCode,
Err: fmt.Errorf(cryptoDepositResponse.Message),
}
}
return CryptoDepositResponse{}, fmt.Errorf("status: %d\nerror: %s", resp.StatusCode, cryptoDepositResponse.Message)
} else if err != nil {
return CryptoDepositResponse{}, &ErrJSONDecoding{Err: err}
}
return cryptoDepositResponse, nil
}
func (c *Client) ethereumInit(ctx context.Context, rpcURL string) error {
if c.ethClient == nil {
ethClient, err := ethclient.Dial(rpcURL)
if err != nil {
return err
}
coinStatus, err := c.getCoinStatus(ctx)
if err != nil {
return err
}
var starkaddr common.Address
var starkexContract StarkexContract
switch c.network {
case TESTNET:
starkaddr = common.HexToAddress(TESTNET_STARK_CONTRACT)
starkexContract, err = contract.NewDepositTestnet(starkaddr, ethClient)
case MAINNET:
starkaddr = common.HexToAddress(MAINET_STARK_CONTRACT)
starkexContract, err = contract.NewDepositMainnet(starkaddr, ethClient)
default:
return ErrInvalidNetwork
}
if err != nil {
return err
}
c.ethClient = ethClient
c.coinStatus = coinStatus
c.starkexContract = starkexContract
c.starkexContractAddress = starkaddr
}
return nil
}
/*
Granting permission for token spending enables transactions on Ethereum.
Supported EVM cross-chain networks: 'ETHEREUM', 'POLYGON', 'OPTIMISM', 'ARBITRUM', 'LINEA', 'SCROLL', 'MODE'.
*/
func (c *Client) SetEthereumAllowance(ctx context.Context, rpcURL string, ethPrivateKey string, currency Currency, amount float64) error {
err := c.ethereumInit(ctx, rpcURL)
if err != nil {
return err
}
coinStatus, err := getCoinStatusPayload(currency, c.coinStatus.Payload)
if err != nil {
return err
}
blockchainDecimal, err := strconv.Atoi(coinStatus.BlockchainDecimal)
if err != nil {
return err
}
decimal, err := strconv.Atoi(coinStatus.Decimal)
if err != nil {
return err
}
privateKey, err := crypto.HexToECDSA(ethPrivateKey)
if err != nil {
return err
}
signerFn := func(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
chainID, err := c.ethClient.ChainID(context.Background())
if err != nil {
return nil, err
}
signedTx, err := types.SignTx(tx, types.NewLondonSigner(chainID), privateKey)
if err != nil {
return nil, err
}
return signedTx, nil
}
opt, err := getTransactionOpt(ctx, c.ethClient, ethPrivateKey, signerFn, 0, decimal)
if err != nil {
return err
}
err = setAllowance(ctx, c.ethClient, coinStatus.TokenContract, opt, c.starkexContractAddress, blockchainDecimal, amount)
if err != nil {
return err
}
return nil
}
type StarkexContract interface {
DepositEth(opts *bind.TransactOpts, starkKey *big.Int, assetType *big.Int, vaultId *big.Int) (*types.Transaction, error)
DepositERC20(opts *bind.TransactOpts, starkKey *big.Int, assetType *big.Int, vaultId *big.Int, quantizedAmount *big.Int) (*types.Transaction, error)
GetWithdrawalBalance(opts *bind.CallOpts, ownerKey *big.Int, assetId *big.Int) (*big.Int, error)
Withdraw(opts *bind.TransactOpts, ownerKey *big.Int, assetType *big.Int) (*types.Transaction, error)
}
/*
In this method, you will use an ETH private key, stark public key and an RPC URL to execute a deposit.
You'll also need to create an RPC URL using services like Infura, Alchemy, etc.
*/
func (c *Client) DepositFromEthereumNetwork(
ctx context.Context,
rpcURL string,
ethAddress string,
ethPrivateKey string,
starkPublicKey string,
amount float64,
currency Currency,
) (CryptoDepositResponse, error) {
// check amount
if amount < 0 {
return CryptoDepositResponse{}, ErrInvalidAmount
}
// check if logged in or not
err := c.CheckAuth()
if err != nil {
return CryptoDepositResponse{}, err
}
// one time setup
err = c.ethereumInit(ctx, rpcURL)
if err != nil {
return CryptoDepositResponse{}, err
}
// extracting specific currency information
coinStatus, err := getCoinStatusPayload(currency, c.coinStatus.Payload)
if err != nil {
return CryptoDepositResponse{}, err
}
// getting vault id here
vaultID, err := c.getVaultID(ctx, currency)
if err != nil {
return CryptoDepositResponse{}, err
}
// Getting balance information here
balance, err := getTokenBalance(ctx, c.ethClient, ethAddress, currency, coinStatus.BlockchainDecimal, coinStatus.TokenContract)
if err != nil {
return CryptoDepositResponse{}, err
}
if balance.Cmp(big.NewFloat(amount)) == -1 {
return CryptoDepositResponse{}, fmt.Errorf("current balance of %v is less than deposit amount %v", balance, amount)
}
var transaction *types.Transaction
starkPublicKeyBigInt, ok := new(big.Int).SetString(starkPublicKey[2:], 16)
if !ok {
return CryptoDepositResponse{}, fmt.Errorf("failed to convert starkPublicKey to big.Int")
}
starkAssetIDBigInt, ok := new(big.Int).SetString(coinStatus.StarkAssetID[2:], 16)
if !ok {
return CryptoDepositResponse{}, fmt.Errorf("failed to convert StarkAssetID to big.Int")
}
vaultIDBigInt := big.NewInt(int64(vaultID))
// decimal
decimal, err := strconv.Atoi(coinStatus.Decimal)
if err != nil {
return CryptoDepositResponse{}, err
}
// blockchain decimal
blockchainDecimal, err := strconv.Atoi(coinStatus.BlockchainDecimal)
if err != nil {
return CryptoDepositResponse{}, err
}
// quantization
quantization, err := strconv.Atoi(coinStatus.Quanitization)
if err != nil {
return CryptoDepositResponse{}, err
}
quantizedAmount := toWei(amount, quantization)
// signer function
privateKey, err := crypto.HexToECDSA(ethPrivateKey)
if err != nil {
return CryptoDepositResponse{}, err
}
signerFn := func(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
chainID, err := c.ethClient.ChainID(context.Background())
if err != nil {
return nil, err
}
signedTx, err := types.SignTx(tx, types.NewLondonSigner(chainID), privateKey)
if err != nil {
return nil, err
}
return signedTx, nil
}
if currency == ETH {
opt, err := getTransactionOpt(ctx, c.ethClient, ethPrivateKey, signerFn, amount, blockchainDecimal)
if err != nil {
return CryptoDepositResponse{}, err
}
transaction, err = c.starkexContract.DepositEth(opt, starkPublicKeyBigInt, starkAssetIDBigInt, vaultIDBigInt)
if err != nil {
return CryptoDepositResponse{}, err
}
} else {
opt, err := getTransactionOpt(ctx, c.ethClient, ethPrivateKey, signerFn, 0, decimal)
if err != nil {
return CryptoDepositResponse{}, err
}
allowance, err := getAllowance(c.ethClient, ethAddress, coinStatus.TokenContract, blockchainDecimal, c.starkexContractAddress)
if err != nil {
return CryptoDepositResponse{}, err
}
if allowance < amount {
return CryptoDepositResponse{},
&ErrInsufficientAllowance{
Allowance: allowance,
Amount: amount,
}
}
transaction, err = c.starkexContract.DepositERC20(opt, starkPublicKeyBigInt, starkAssetIDBigInt, vaultIDBigInt, quantizedAmount)
if err != nil {
return CryptoDepositResponse{}, err
}
}
var starkAssetId string
if coinStatus.StarkAssetID[0:3] == "0x0" {
starkAssetId = "0x" + coinStatus.StarkAssetID[3:]
} else {
starkAssetId = coinStatus.StarkAssetID
}
resp, err := c.cryptoDepositStart(ctx, CryptoDepositRequest{
Amount: quantizedAmount.String(),
StarkAssetID: starkAssetId,
StarkPublicKey: starkPublicKey,
DepositBlockchainHash: transaction.Hash().Hex(),
DepositBlockchainNonce: fmt.Sprintf("%v", transaction.Nonce()),
VaultID: vaultID,
})
if err != nil {
return CryptoDepositResponse{}, err
}
resp.Payload = transaction.Hash().Hex()
return resp, nil
}