-
Notifications
You must be signed in to change notification settings - Fork 21
/
sell_knc.js
178 lines (160 loc) · 5.78 KB
/
sell_knc.js
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
// Import web3 for broadcasting transactions
var Web3 = require('web3');
// Import node-fetch to query the trading API
var fetch = require('node-fetch');
// import ethereumjs-tx to sign and serialise transactions
var Tx = require('ethereumjs-tx').Transaction;
const NETWORK = "ropsten";
const PROJECT_ID = "ENTER YOUR PROJECT ID";
// Connect to Infura’s ropsten node
const web3 = new Web3(new Web3.providers.HttpProvider(`https://${NETWORK}.infura.io/v3/${PROJECT_ID}`));
const NETWORK_URL = `https://${NETWORK}-api.kyber.network`;
// Representation of ETH as an address on Ropsten
const ETH_TOKEN_ADDRESS = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee';
// KNC contract address on Ropsten
const KNC_TOKEN_ADDRESS = '0x4E470dc7321E84CA96FcAEDD0C8aBCebbAEB68C6';
const ETH_DECIMALS = 18;
const KNC_DECIMALS = 18;
// How many KNC you want to sell
const QTY = 100;
// Gas price of the transaction
const GAS_PRICE = 'medium';
const USER_ACCOUNT = 'ENTER YOUR WALLET ADDRESS';
const PRIVATE_KEY = Buffer.from('ENTER YOUR PRIVATE KEY', 'hex');
async function main() {
/*
#################################
### CHECK IF KNC IS SUPPORTED ###
#################################
*/
// Querying the API /currencies endpoint
let tokenInfoRequest = await fetch(
`${NETWORK_URL}/currencies`
);
// Parsing the output
let tokens = await tokenInfoRequest.json();
console.log(JSON.stringify(tokens));
// Checking to see if KNC is supported
let supported = tokens.data.some(token => {
return "KNC" == token.symbol;
});
// If not supported, return.
if (!supported) {
console.log("Token is not supported");
return;
}
/*
####################################
### GET ETH/KNC CONVERSION RATES ###
####################################
*/
// Querying the API /buy_rate endpoint
/* let ratesRequest = await fetch(
"https://ropsten-api.kyber.network/buy_rate?id=" +
KNC_TOKEN_ADDRESS +
"&qty=" +
QTY
);
// Parsing the output
let rates = await ratesRequest.json();
console.log(JSON.stringify(rates));
// Getting the source quantity
let srcQty = rates.data[0].src_qty; */
/*
####################################
### GET ENABLED STATUS OF WALLET ###
####################################
*/
// Querying the API /users/<user_address>/currencies endpoint
let enabledStatusesRequest = await fetch(
"https://ropsten-api.kyber.network/users/" + USER_ACCOUNT + "/currencies"
);
// Parsing the output
let enabledStatuses = await enabledStatusesRequest.json();
// Checking to see if DAI is enabled
let enabled = enabledStatuses.data.some(token => {
if (token.id == KNC_TOKEN_ADDRESS.toLowerCase()) {
return token.enabled;
}
});
/*
####################################
### ENABLE WALLET IF NOT ENABLED ###
####################################
*/
if (!enabled) {
// Querying the API /users/<user_address>/currencies/<currency_id>/enable_data?gas_price=<gas_price> endpoint
let enableTokenDetailsRequest = await fetch(
"https://ropsten-api.kyber.network/users/" +
USER_ACCOUNT +
"/currencies/" +
KNC_TOKEN_ADDRESS +
"/enable_data?gas_price=" +
GAS_PRICE
);
// Parsing the output
let enableTokenDetails = await enableTokenDetailsRequest.json();
// Extract the raw transaction details
let rawTx = enableTokenDetails.data;
console.log(rawTx);
// Create a new transaction
let tx = new Tx(rawTx, { 'chain': 'ropsten' });
// Signing the transaction
tx.sign(PRIVATE_KEY);
// Serialise the transaction (RLP encoding)
let serializedTx = tx.serialize();
// Broadcasting the transaction
txReceipt = await web3.eth
.sendSignedTransaction("0x" + serializedTx.toString("hex"))
.catch(error => console.log(error));
// Log the transaction receipt
console.log(txReceipt);
}
/*
#######################
### TRADE EXECUTION ###
#######################
*/
// Querying the API /trade_data endpoint
// Note that a factor of 0.97 is used to account for slippage but you can use any value you want.
let destAmount = await getQuoteAmount(KNC_TOKEN_ADDRESS, ETH_TOKEN_ADDRESS, QTY);
let tradeDetailsRequest = await fetch(
`${NETWORK_URL}/trade_data?user_address=` +
USER_ACCOUNT +
"&src_id=" +
KNC_TOKEN_ADDRESS +
"&dst_id=" +
ETH_TOKEN_ADDRESS +
"&src_qty=" +
QTY +
"&min_dst_qty=" +
destAmount +
"&gas_price=" +
GAS_PRICE
// "&wallet_id=" +
// WALLET_ID
);
let tradeDetails = await tradeDetailsRequest.json();
// Extract the raw transaction details
let rawTx = tradeDetails.data[0];
console.log("Planning to send: ", rawTx);
// Create a new transaction
let tx = new Tx(rawTx, { 'chain': 'ropsten' });
// Signing the transaction
tx.sign(PRIVATE_KEY);
// Serialise the transaction (RLP encoding)
let serializedTx = tx.serialize();
// Broadcasting the transaction
txReceipt = await web3.eth
.sendSignedTransaction("0x" + serializedTx.toString("hex"))
.catch(error => console.log(error));
// Log the transaction receipt
console.log("Transaction DONE! Receipt: ", txReceipt);
}
async function getQuoteAmount(srcToken, destToken, srcQty) {
let quoteAmountRequest = await fetch(`${NETWORK_URL}/quote_amount?base=${srcToken}"e=${destToken}&base_amount=${srcQty}&type=sell`)
let quoteAmount = await quoteAmountRequest.json();
quoteAmount = quoteAmount.data;
return quoteAmount * 0.97;
}
main();