-
Notifications
You must be signed in to change notification settings - Fork 652
/
getOriginalAsset.ts
382 lines (361 loc) · 10.3 KB
/
getOriginalAsset.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
import { JsonRpcProvider } from "@mysten/sui.js";
import {
Commitment,
Connection,
PublicKey,
PublicKeyInitData,
} from "@solana/web3.js";
import { LCDClient as TerraLCDClient } from "@terra-money/terra.js";
import { LCDClient as XplaLCDClient } from "@xpla/xpla.js";
import { Algodv2 } from "algosdk";
import { AptosClient } from "aptos";
import { ethers } from "ethers";
import { arrayify, sha256, zeroPad } from "ethers/lib/utils";
import { sha3_256 } from "js-sha3";
import { Provider } from "near-api-js/lib/providers";
import { decodeLocalState } from "../algorand";
import { OriginInfo } from "../aptos/types";
import { canonicalAddress } from "../cosmos";
import { buildTokenId, isNativeCosmWasmDenom } from "../cosmwasm/address";
import { TokenImplementation__factory } from "../ethers-contracts";
import { getWrappedMeta } from "../solana/tokenBridge";
import {
getFieldsFromObjectResponse,
getTokenFromTokenRegistry,
isValidSuiType,
trimSuiType,
} from "../sui";
import { buildNativeId } from "../terra";
import {
CHAIN_ID_ALGORAND,
CHAIN_ID_APTOS,
CHAIN_ID_NEAR,
CHAIN_ID_SOLANA,
CHAIN_ID_SUI,
CHAIN_ID_TERRA,
ChainId,
ChainName,
CosmWasmChainId,
CosmWasmChainName,
assertChain,
callFunctionNear,
coalesceChainId,
coalesceCosmWasmChainId,
hexToUint8Array,
isValidAptosType,
} from "../utils";
import { safeBigIntToNumber } from "../utils/bigint";
import {
getIsWrappedAssetAlgorand,
getIsWrappedAssetEth,
getIsWrappedAssetNear,
} from "./getIsWrappedAsset";
// TODO: remove `as ChainId` and return number in next minor version as we can't ensure it will match our type definition
export interface WormholeWrappedInfo {
isWrapped: boolean;
chainId: ChainId;
assetAddress: Uint8Array;
}
/**
* Returns a origin chain and asset address on {originChain} for a provided Wormhole wrapped address
* @param tokenBridgeAddress
* @param provider
* @param wrappedAddress
* @returns
*/
export async function getOriginalAssetEth(
tokenBridgeAddress: string,
provider: ethers.Signer | ethers.providers.Provider,
wrappedAddress: string,
lookupChain: ChainId | ChainName
): Promise<WormholeWrappedInfo> {
const isWrapped = await getIsWrappedAssetEth(
tokenBridgeAddress,
provider,
wrappedAddress
);
if (isWrapped) {
const token = TokenImplementation__factory.connect(
wrappedAddress,
provider
);
const chainId = (await token.chainId()) as ChainId; // origin chain
const assetAddress = await token.nativeContract(); // origin address
return {
isWrapped: true,
chainId,
assetAddress: arrayify(assetAddress),
};
}
return {
isWrapped: false,
chainId: coalesceChainId(lookupChain),
assetAddress: zeroPad(arrayify(wrappedAddress), 32),
};
}
export async function getOriginalAssetTerra(
client: TerraLCDClient,
wrappedAddress: string
) {
return getOriginalAssetCosmWasm(client, wrappedAddress, CHAIN_ID_TERRA);
}
export async function getOriginalAssetXpla(
client: XplaLCDClient,
wrappedAddress: string
) {
return getOriginalAssetCosmWasm(client, wrappedAddress, "xpla");
}
export async function getOriginalAssetCosmWasm(
client: TerraLCDClient | XplaLCDClient,
wrappedAddress: string,
lookupChain: CosmWasmChainId | CosmWasmChainName
): Promise<WormholeWrappedInfo> {
const chainId = coalesceCosmWasmChainId(lookupChain);
if (isNativeCosmWasmDenom(chainId, wrappedAddress)) {
return {
isWrapped: false,
chainId: chainId,
assetAddress:
chainId === CHAIN_ID_TERRA
? buildNativeId(wrappedAddress)
: hexToUint8Array(buildTokenId(chainId, wrappedAddress)),
};
}
try {
const result: {
asset_address: string;
asset_chain: ChainId;
bridge: string;
} = await client.wasm.contractQuery(wrappedAddress, {
wrapped_asset_info: {},
});
if (result) {
return {
isWrapped: true,
chainId: result.asset_chain,
assetAddress: new Uint8Array(
Buffer.from(result.asset_address, "base64")
),
};
}
} catch (e) {}
return {
isWrapped: false,
chainId: chainId,
assetAddress:
chainId === CHAIN_ID_TERRA
? zeroPad(canonicalAddress(wrappedAddress), 32)
: hexToUint8Array(buildTokenId(chainId, wrappedAddress)),
};
}
/**
* Returns a origin chain and asset address on {originChain} for a provided Wormhole wrapped address
* @param connection
* @param tokenBridgeAddress
* @param mintAddress
* @param [commitment]
* @returns
*/
export async function getOriginalAssetSolana(
connection: Connection,
tokenBridgeAddress: PublicKeyInitData,
mintAddress: PublicKeyInitData,
commitment?: Commitment
): Promise<WormholeWrappedInfo> {
try {
const mint = new PublicKey(mintAddress);
return getWrappedMeta(
connection,
tokenBridgeAddress,
mintAddress,
commitment
)
.catch((_) => null)
.then((meta) => {
if (meta === null) {
return {
isWrapped: false,
chainId: CHAIN_ID_SOLANA,
assetAddress: mint.toBytes(),
};
} else {
return {
isWrapped: true,
chainId: meta.chain as ChainId,
assetAddress: Uint8Array.from(meta.tokenAddress),
};
}
});
} catch (_) {
return {
isWrapped: false,
chainId: CHAIN_ID_SOLANA,
assetAddress: new Uint8Array(32),
};
}
}
export const getOriginalAssetSol = getOriginalAssetSolana;
/**
* Returns an origin chain and asset address on {originChain} for a provided Wormhole wrapped address
* @param client Algodv2 client
* @param tokenBridgeId Application ID of the token bridge
* @param assetId Algorand asset index
* @returns wrapped wormhole information structure
*/
export async function getOriginalAssetAlgorand(
client: Algodv2,
tokenBridgeId: bigint,
assetId: bigint
): Promise<WormholeWrappedInfo> {
let retVal: WormholeWrappedInfo = {
isWrapped: false,
chainId: CHAIN_ID_ALGORAND,
assetAddress: new Uint8Array(),
};
retVal.isWrapped = await getIsWrappedAssetAlgorand(
client,
tokenBridgeId,
assetId
);
if (!retVal.isWrapped) {
retVal.assetAddress = zeroPad(arrayify(ethers.BigNumber.from(assetId)), 32);
return retVal;
}
const assetInfo = await client.getAssetByID(safeBigIntToNumber(assetId)).do();
const lsa = assetInfo.params.creator;
const dls = await decodeLocalState(client, tokenBridgeId, lsa);
const dlsBuffer: Buffer = Buffer.from(dls);
retVal.chainId = dlsBuffer.readInt16BE(92) as ChainId;
retVal.assetAddress = new Uint8Array(dlsBuffer.slice(60, 60 + 32));
return retVal;
}
export async function getOriginalAssetNear(
provider: Provider,
tokenAccount: string,
assetAccount: string
): Promise<WormholeWrappedInfo> {
const retVal: WormholeWrappedInfo = {
isWrapped: false,
chainId: CHAIN_ID_NEAR,
assetAddress: new Uint8Array(),
};
retVal.isWrapped = getIsWrappedAssetNear(tokenAccount, assetAccount);
if (!retVal.isWrapped) {
retVal.assetAddress = assetAccount
? arrayify(sha256(Buffer.from(assetAccount)))
: zeroPad(arrayify("0x"), 32);
return retVal;
}
const buf = await callFunctionNear(
provider,
tokenAccount,
"get_original_asset",
{
token: assetAccount,
}
);
retVal.chainId = buf[1];
retVal.assetAddress = hexToUint8Array(buf[0]);
return retVal;
}
/**
* Gets the origin chain ID and address of an asset on Aptos, given its fully qualified type.
* @param client Client used to transfer data to/from Aptos node
* @param tokenBridgePackageId Address of token bridge
* @param fullyQualifiedType Fully qualified type of asset
* @returns Original chain ID and address of asset
*/
export async function getOriginalAssetAptos(
client: AptosClient,
tokenBridgePackageId: string,
fullyQualifiedType: string
): Promise<WormholeWrappedInfo> {
if (!isValidAptosType(fullyQualifiedType)) {
throw new Error("Invalid qualified type");
}
let originInfo: OriginInfo | undefined;
try {
originInfo = (
await client.getAccountResource(
fullyQualifiedType.split("::")[0],
`${tokenBridgePackageId}::state::OriginInfo`
)
).data as OriginInfo;
} catch {
return {
isWrapped: false,
chainId: CHAIN_ID_APTOS,
assetAddress: hexToUint8Array(sha3_256(fullyQualifiedType)),
};
}
if (!!originInfo) {
// wrapped asset
const chainId = parseInt(originInfo.token_chain.number);
assertChain(chainId);
const assetAddress = hexToUint8Array(
originInfo.token_address.external_address.substring(2)
);
return {
isWrapped: true,
chainId,
assetAddress,
};
} else {
// native asset
return {
isWrapped: false,
chainId: CHAIN_ID_APTOS,
assetAddress: hexToUint8Array(sha3_256(fullyQualifiedType)),
};
}
}
export async function getOriginalAssetSui(
provider: JsonRpcProvider,
tokenBridgeStateObjectId: string,
coinType: string
): Promise<WormholeWrappedInfo> {
if (!isValidSuiType(coinType)) {
throw new Error(`Invalid Sui type: ${coinType}`);
}
const res = await getTokenFromTokenRegistry(
provider,
tokenBridgeStateObjectId,
coinType
);
const fields = getFieldsFromObjectResponse(res);
if (!fields) {
throw new Error(
`Token of type ${coinType} has not been registered with the token bridge`
);
}
// Normalize types
const type = trimSuiType(fields.value.type);
coinType = trimSuiType(coinType);
// Check if wrapped or native asset. We check inclusion instead of equality
// because it saves us from making an additional RPC call to fetch the
// package ID.
if (type.includes(`wrapped_asset::WrappedAsset<${coinType}>`)) {
return {
isWrapped: true,
chainId: Number(fields.value.fields.info.fields.token_chain) as ChainId,
assetAddress: new Uint8Array(
fields.value.fields.info.fields.token_address.fields.value.fields.data
),
};
} else if (type.includes(`native_asset::NativeAsset<${coinType}>`)) {
return {
isWrapped: false,
chainId: CHAIN_ID_SUI,
assetAddress: new Uint8Array(
fields.value.fields.token_address.fields.value.fields.data
),
};
}
throw new Error(
`Unrecognized token metadata: ${JSON.stringify(
fields,
null,
2
)}, ${coinType}`
);
}