-
Notifications
You must be signed in to change notification settings - Fork 77
/
XcmRepository.ts
383 lines (340 loc) · 10.6 KB
/
XcmRepository.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
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
import { u8aToString, BN } from '@polkadot/util';
import { QueryableStorageMultiArg } from '@polkadot/api/types';
import { PalletAssetsAssetAccount } from '@polkadot/types/lookup';
import { Option, Struct } from '@polkadot/types';
import Web3 from 'web3';
import { Asset, AssetMetadata } from 'src/v2/models';
import { IXcmRepository } from 'src/v2/repositories';
import { injectable, inject } from 'inversify';
import { ExtrinsicPayload, IApi, IApiFactory } from 'src/v2/integration';
import { Symbols } from 'src/v2/symbols';
import { Guard } from 'src/v2/common';
import {
getPubkeyFromSS58Addr,
isValidAddressPolkadotAddress,
isValidEvmAddress,
} from '@astar-network/astar-sdk-core';
import { XcmTokenInformation } from 'src/modules/xcm';
import { decodeAddress, evmToAddress } from '@polkadot/util-crypto';
import { TokenId } from 'src/v2/config/types';
import { Chain, XcmChain } from 'src/v2/models/XcmModels';
import { FrameSystemAccountInfo } from 'src/v2/repositories/implementations/SystemRepository';
import { ethers } from 'ethers';
import { usdtMinFeeAmount } from 'src/modules/xcm/tokens';
interface AssetConfig extends Struct {
v1: {
parents: number;
interior: Interior;
};
}
interface Interior {
x2: X2[];
}
interface X2 {
parachain: number;
generalKey: string;
}
export const ASTAR_ADDRESS_PREFIX = 5;
@injectable()
export class XcmRepository implements IXcmRepository {
// Ids of Astar tokens on foreign network. To be initialized in iherited class.
protected astarTokens: TokenId;
constructor(
@inject(Symbols.DefaultApi) protected api: IApi,
@inject(Symbols.ApiFactory) protected apiFactory: IApiFactory,
@inject(Symbols.RegisteredTokens) private registeredTokens: XcmTokenInformation[]
) {
this.astarTokens = {};
}
public async getAssets(currentAccount: string): Promise<Asset[]> {
Guard.ThrowIfUndefined('currentAccount', currentAccount);
const api = await this.api.getApi();
const metadata = await api.query.assets.metadata.entries();
let result: Asset[] = [];
if (metadata.length > 0) {
metadata.forEach(([key, value]) => {
const id = key.args.map((x) => x.toString())[0];
const deposit = value.deposit.toString();
const name = u8aToString(value.name);
const symbol = u8aToString(value.symbol);
const decimals = value.decimals.toNumber();
const isFrozen = value.isFrozen.valueOf();
const metadata = new AssetMetadata(name, symbol, decimals, isFrozen, deposit);
const registeredData = this.registeredTokens.find((x) => x.assetId === id);
const minBridgeAmount = registeredData ? registeredData.minBridgeAmount : '0';
const originChain = registeredData ? registeredData.originChain : '';
const originAssetId = registeredData ? registeredData.originAssetId : '';
const tokenImage = registeredData ? (registeredData.logo as string) : 'custom-token';
const isNativeToken = registeredData ? registeredData.isNativeToken : false;
const isXcmCompatible = registeredData ? registeredData.isXcmCompatible : false;
const userBalance = 0;
const asset = new Asset(
id,
this.getMappedXC20Asset(id),
metadata,
minBridgeAmount,
originChain,
originAssetId,
tokenImage,
isNativeToken,
isXcmCompatible,
userBalance
);
result.push(asset);
});
if (isValidAddressPolkadotAddress(currentAccount)) {
// fetch balances for Substrate accounts only.
result = await this.getBalances(currentAccount, result);
}
}
return result;
}
public getXcmVersion(from: XcmChain): { version: string; isV3: boolean } {
// e.g.: [Chain.BIFROST_KUSAMA]
const v3s: Chain[] = [];
const version = v3s.find((it) => it === from.name) ? 'V3' : 'V1';
const isV3 = version === 'V3';
return { version, isV3 };
}
public async getTransferToParachainCall(
from: XcmChain,
to: XcmChain,
recipientAddress: string,
token: Asset,
amount: BN,
endpoint: string
): Promise<ExtrinsicPayload> {
if (!to.parachainId) {
throw `Parachain id for ${to.name} is not defined`;
}
const version = 'V3';
// the target parachain connected to the current relaychain
const destination = {
[version]: {
interior: {
X1: {
Parachain: new BN(to.parachainId),
},
},
parents: new BN(0),
},
};
const recipientAddressId = this.getAddress(recipientAddress);
const id = decodeAddress(recipientAddressId);
const AccountId32 = {
id,
};
const beneficiary = {
[version]: {
interior: {
X1: {
AccountId32,
},
},
parents: new BN(0),
},
};
const assets = {
[version]: [
{
fun: {
Fungible: amount,
},
id: {
Concrete: {
interior: 'Here',
parents: new BN(0),
},
},
},
],
};
return await this.buildTxCall(
from,
endpoint,
'xcmPallet',
'reserveTransferAssets',
destination,
beneficiary,
assets,
new BN(0)
);
}
public async getTransferToOriginChainCall(
from: XcmChain,
recipientAddress: string,
amount: BN,
endpoint: string
): Promise<ExtrinsicPayload> {
const recipientAccountId = getPubkeyFromSS58Addr(recipientAddress);
const asset = {
Concrete: {
interior: 'Here',
parents: new BN(1),
},
};
const assets = {
V3: {
fun: {
Fungible: new BN(amount),
},
id: asset,
},
};
const destination = {
V3: {
interior: {
X1: {
AccountId32: {
id: decodeAddress(recipientAccountId),
},
},
},
parents: new BN(1),
},
};
const weightLimit = {
Unlimited: null,
};
return await this.buildTxCall(
from,
endpoint,
'xTokens',
'transferMultiasset',
assets,
destination,
weightLimit
);
}
public getTransferCall(
from: XcmChain,
to: XcmChain,
recipientAddress: string,
token: Asset,
amount: BN,
endpoint: string
): Promise<ExtrinsicPayload> {
throw 'Not implemented.';
}
public async getTokenBalance(
address: string,
chain: XcmChain,
token: Asset,
isNativeToken: boolean,
endpoint: string
): Promise<string> {
return (await this.getNativeBalance(address, chain, endpoint)).toString();
}
public async getNativeBalance(address: string, chain: XcmChain, endpoint: string): Promise<BN> {
try {
const api = await this.apiFactory.get(endpoint);
const { data } = await api.query.system.account<FrameSystemAccountInfo>(address);
return (data.free.toBn() as BN).sub(new BN(data.miscFrozen ?? data.frozen));
} catch (e) {
console.error(e);
return new BN(0);
}
}
protected async buildTxCall(
network: XcmChain,
endpoint: string,
extrinsic: string,
method: string,
...args: any[]
): Promise<ExtrinsicPayload> {
const api = await this.apiFactory.get(endpoint);
const call = api.tx[extrinsic][method](...args);
if (call) {
return call;
}
throw `Undefined extrinsic call ${extrinsic} with method ${method}`;
}
protected async fetchAssetConfigById(
source: XcmChain,
tokenId: string,
endpoint: string
): Promise<{
parents: number;
interior: Interior;
}> {
const api = await this.apiFactory.get(endpoint);
const config = await api.query.xcAssetConfig.assetIdToLocation<Option<AssetConfig>>(tokenId);
const formattedAssetConfig = JSON.parse(config.toString());
return formattedAssetConfig.v3;
}
protected async fetchAssetConfig(
source: XcmChain,
token: Asset,
endpoint: string
): Promise<{
parents: number;
interior: Interior;
}> {
return this.fetchAssetConfigById(source, token.id, endpoint);
}
protected isAstarNativeToken(token: Asset): boolean {
return !!this.astarTokens[token.metadata.symbol];
}
private async getBalances(address: string, assets: Asset[]): Promise<Asset[]> {
const queries: QueryableStorageMultiArg<'promise'>[] = [];
const api = await this.api.getApi();
// Build and issue multi query request
assets.map((x) => queries.push([api.query.assets.account, [new BN(x.id), address]]));
const balancesOption = await api.queryMulti<Option<PalletAssetsAssetAccount>[]>(queries);
balancesOption.map((x, index) => {
if (x.isSome) {
const balance = x.unwrap();
assets[index].balance = balance.balance.toString();
}
});
return assets;
}
private getAddress(address: string): string {
if (isValidAddressPolkadotAddress(address)) {
return address;
} else if (isValidEvmAddress(address)) {
const ss58MappedAddr = evmToAddress(address, ASTAR_ADDRESS_PREFIX);
const hexPublicKey = getPubkeyFromSS58Addr(ss58MappedAddr);
return hexPublicKey;
} else {
throw `The address ${address} is not valid.`;
}
}
private getMappedXC20Asset(assetId: string): string {
const hexedAddress = `0xffffffff${Web3.utils.toHex(assetId).slice(2)}`;
const requirementLength = 42;
const mappedLength = hexedAddress.length;
const paddingDiffer = requirementLength - mappedLength;
if (paddingDiffer === 0) {
return hexedAddress;
} else {
// Memo: modify the mapped address due to padding issue
// Memo: -> 0xffffffff
const a = hexedAddress.slice(0, 10);
const b = '0'.repeat(paddingDiffer);
const c = hexedAddress.slice(10);
const fixedAddress = a + b + c;
return fixedAddress;
}
}
protected getFeeInformation(
token: Asset,
source: XcmChain,
destination: XcmChain
): {
feeAssetIsRequired: boolean;
feeAssetId: string;
feeAmount: number;
} {
if (token.metadata.name === 'PINK' && destination.name === Chain.ASSET_HUB) {
// Pink is not a sufficient token and cannot be used as gas fee in Asset Hub,
// it means we need to transfer another token to pay the fee and we will use USDT token.
const feeAssetIsRequired = true;
// 4294969280 is the USDT id
const feeAssetId = '4294969280';
const feeAmount = Number(ethers.utils.parseUnits(String(usdtMinFeeAmount), 6).toString());
return { feeAssetIsRequired, feeAssetId, feeAmount };
}
return { feeAssetIsRequired: false, feeAssetId: '', feeAmount: 0 };
}
}