forked from albertov19/xcmTools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculateBatchUnitsPerSeconds.ts
191 lines (167 loc) · 4.99 KB
/
calculateBatchUnitsPerSeconds.ts
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
import { ApiPromise, WsProvider } from '@polkadot/api';
import { MultiLocation } from '@polkadot/types/interfaces';
import axios from 'axios';
import assetsJSON from './assets.json';
import yargs from 'yargs';
import 'dotenv/config';
let args = yargs.options({
network: { type: 'string', demandOption: true, alias: 'n' },
'xcm-weight-cost': {
type: 'string',
demandOption: true,
alias: 'xwc',
default: 1000000000,
},
target: { type: 'string', demandOption: true, alias: 't', default: '0.02' },
}).argv;
let wsEndpoint;
switch (args['network'].toLowerCase()) {
case 'moonbeam':
wsEndpoint = 'wss://wss.api.moonbeam.network';
break;
case 'moonriver':
wsEndpoint = 'wss://wss.api.moonriver.moonbeam.network';
break;
case 'moonbase':
wsEndpoint = 'wss://wss.api.moonbase.moonbeam.network';
break;
default:
console.error('Supported network are Moonbeam and Moonriver');
}
let networkAssets = assetsJSON[args['network']];
// Create Provider
const wsProvider = new WsProvider(wsEndpoint);
// Variables
const batchTxs = [];
async function main() {
// Wait for Provider
const api = await ApiPromise.create({
provider: wsProvider,
noInitWarn: true,
});
await api.isReady;
// Get Length of assets
let numSupportedAssets = (
(await api.query.assetManager.supportedFeePaymentAssets()) as any
).length;
// For Loop Through Assets
for (let asset in networkAssets) {
// Get MultiLocation
let assetML: MultiLocation = api.createType(
'StagingXcmV3MultiLocation',
(
await api.query.assetManager.assetIdType(networkAssets[asset].assetID)
).toJSON()['xcm']
);
// Check The Asset is a Fee Asset
let checkAsset = await api.query.assetManager.assetTypeUnitsPerSecond({
Xcm: assetML,
});
if (checkAsset.toHuman() !== null) {
// Get Assets Decimals
let decimals = (
await api.query.assets.metadata(networkAssets[asset].assetID)
)
.toJSON()
['decimals'].toString();
//Build Args for Function
args = {
decimals: decimals,
name: networkAssets[asset]['name'],
asset: networkAssets[asset]['api-name'],
target: args['target'],
xwc: args['xwc'],
};
if (networkAssets[asset]['price']) {
args.price = networkAssets[asset]['price'];
}
// Calcualte Units Per Second
let unitsPerSeconds = await calculateUnitsPerSecond(args);
// Batch Tx
batchTxs.push(
await api.tx.assetManager.setAssetUnitsPerSecond(
{ Xcm: assetML },
unitsPerSeconds,
numSupportedAssets + 10
)
);
} else {
throw new Error(
`Script could not check Units Per Second for ${networkAssets[asset].name} - Check types!`
);
}
}
// Batch Tx
const batchCall = api.tx.utility.batchAll(batchTxs);
console.log(
'Encoded proposal for batchCall is %s',
batchCall.method.toHex() || ''
);
}
async function calculateUnitsPerSecond(args) {
// Target Price in USD
const targetPrice = BigInt(10 ** args['decimals'] * args['target']); // 2 CENTS USD
const decimalsFactor = 10 ** args['decimals'];
// XCM Weight Cost
const xcmTotalCost = BigInt(args['xwc']);
let tokenPrice;
let tokenData = {} as any;
// Get Token Price - If not provided it will use CoinGecko API to get it
if (!args['price']) {
if (args['asset']) {
console.log(
`Fetching Price for ${args['name']} - API ID ${args['asset']}`
);
try {
tokenData = await axios.get(
'https://api.coingecko.com/api/v3/simple/price',
{
params: {
ids: args['asset'],
vs_currencies: 'usd',
x_cg_demo_api_key: process.env.COINGECKO_API,
},
headers: {
Accept: 'application/json',
},
}
);
} catch (error) {
throw new Error(
`Something was not right for ${args['asset']} \n ${error}`
);
}
} else {
console.error(
'You need to provide either an asset name with <--a> or a fixed price with <--p>'
);
}
if (tokenData.status === 200 && tokenData.data[args['asset']].usd) {
tokenPrice = BigInt(
Math.round(decimalsFactor * tokenData.data[args['asset']].usd)
);
} else {
throw new Error(
`Something was not right for ${args['asset']} \n ${tokenData.status} - ${tokenData.statusText}`
);
}
} else {
// Use given price
tokenPrice = BigInt(Math.trunc(decimalsFactor * args['price']));
tokenData.status = 200;
}
if (tokenData.status === 200) {
//Calculate Units Per Second
const unitsPerSecond =
(targetPrice * BigInt(10 ** 12) * BigInt(decimalsFactor)) /
(xcmTotalCost * tokenPrice);
return unitsPerSecond;
} else {
console.error(
'Token name not supported, note that is token name and not ticker!'
);
}
}
main()
.catch(console.error)
.finally(() => process.exit());