-
Notifications
You must be signed in to change notification settings - Fork 643
/
attest.ts
353 lines (333 loc) · 10.2 KB
/
attest.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
import {
JsonRpcProvider,
SUI_CLOCK_OBJECT_ID,
TransactionBlock,
} from "@mysten/sui.js";
import {
Commitment,
Connection,
Keypair,
PublicKey,
PublicKeyInitData,
Transaction,
} from "@solana/web3.js";
import { MsgExecuteContract } from "@terra-money/terra.js";
import { MsgExecuteContract as XplaMsgExecuteContract } from "@xpla/xpla.js";
import {
Algodv2,
OnApplicationComplete,
SuggestedParams,
bigIntToBytes,
decodeAddress,
getApplicationAddress,
makeApplicationCallTxnFromObject,
makePaymentTxnWithSuggestedParamsFromObject,
} from "algosdk";
import { Types } from "aptos";
import BN from "bn.js";
import { PayableOverrides, ethers } from "ethers";
import { FunctionCallOptions } from "near-api-js/lib/account";
import { Provider } from "near-api-js/lib/providers";
import { getIsWrappedAssetNear } from ".";
import { TransactionSignerPair, getMessageFee, optin } from "../algorand";
import { attestToken as attestTokenAptos } from "../aptos";
import { isNativeDenomXpla } from "../cosmwasm";
import { Bridge__factory } from "../ethers-contracts";
import { createBridgeFeeTransferInstruction } from "../solana";
import { createAttestTokenInstruction } from "../solana/tokenBridge";
import { getPackageId } from "../sui/utils";
import { isNativeDenom } from "../terra";
import {
ChainId,
callFunctionNear,
hashAccount,
textToHexString,
textToUint8Array,
uint8ArrayToHex,
} from "../utils";
import { safeBigIntToNumber } from "../utils/bigint";
import { createNonce } from "../utils/createNonce";
export async function attestFromEth(
tokenBridgeAddress: string,
signer: ethers.Signer,
tokenAddress: string,
overrides: PayableOverrides & { from?: string | Promise<string> } = {}
): Promise<ethers.ContractReceipt> {
const bridge = Bridge__factory.connect(tokenBridgeAddress, signer);
const v = await bridge.attestToken(tokenAddress, createNonce(), overrides);
const receipt = await v.wait();
return receipt;
}
export async function attestFromTerra(
tokenBridgeAddress: string,
walletAddress: string,
asset: string
): Promise<MsgExecuteContract> {
const nonce = Math.round(Math.random() * 100000);
const isNativeAsset = isNativeDenom(asset);
return new MsgExecuteContract(walletAddress, tokenBridgeAddress, {
create_asset_meta: {
asset_info: isNativeAsset
? {
native_token: { denom: asset },
}
: {
token: {
contract_addr: asset,
},
},
nonce: nonce,
},
});
}
export function attestFromXpla(
tokenBridgeAddress: string,
walletAddress: string,
asset: string
): XplaMsgExecuteContract {
const nonce = Math.round(Math.random() * 100000);
const isNativeAsset = isNativeDenomXpla(asset);
return new XplaMsgExecuteContract(walletAddress, tokenBridgeAddress, {
create_asset_meta: {
asset_info: isNativeAsset
? {
native_token: { denom: asset },
}
: {
token: {
contract_addr: asset,
},
},
nonce: nonce,
},
});
}
export async function attestFromSolana(
connection: Connection,
bridgeAddress: PublicKeyInitData,
tokenBridgeAddress: PublicKeyInitData,
payerAddress: PublicKeyInitData,
mintAddress: PublicKeyInitData,
commitment?: Commitment
): Promise<Transaction> {
const nonce = createNonce().readUInt32LE(0);
const transferIx = await createBridgeFeeTransferInstruction(
connection,
bridgeAddress,
payerAddress
);
const messageKey = Keypair.generate();
const attestIx = createAttestTokenInstruction(
tokenBridgeAddress,
bridgeAddress,
payerAddress,
mintAddress,
messageKey.publicKey,
nonce
);
const transaction = new Transaction().add(transferIx, attestIx);
const { blockhash } = await connection.getLatestBlockhash(commitment);
transaction.recentBlockhash = blockhash;
transaction.feePayer = new PublicKey(payerAddress);
transaction.partialSign(messageKey);
return transaction;
}
/**
* Attest an already created asset
* If you create a new asset on algorand and want to transfer it elsewhere,
* you create an attestation for it on algorand... pass that vaa to the target chain..
* submit it.. then you can transfer from algorand to that target chain
* @param client An Algodv2 client
* @param tokenBridgeId The ID of the token bridge
* @param senderAcct The account paying fees
* @param assetId The asset index
* @returns Transaction ID
*/
export async function attestFromAlgorand(
client: Algodv2,
tokenBridgeId: bigint,
bridgeId: bigint,
senderAddr: string,
assetId: bigint
): Promise<TransactionSignerPair[]> {
const tbAddr: string = getApplicationAddress(tokenBridgeId);
const decTbAddr: Uint8Array = decodeAddress(tbAddr).publicKey;
const aa: string = uint8ArrayToHex(decTbAddr);
const txs: TransactionSignerPair[] = [];
// "attestFromAlgorand::emitterAddr"
const { addr: emitterAddr, txs: emitterOptInTxs } = await optin(
client,
senderAddr,
bridgeId,
BigInt(0),
aa
);
txs.push(...emitterOptInTxs);
let creatorAddr = "";
let creatorAcctInfo;
const bPgmName: Uint8Array = textToUint8Array("attestToken");
if (assetId !== BigInt(0)) {
const assetInfo = await client
.getAssetByID(safeBigIntToNumber(assetId))
.do();
creatorAcctInfo = await client
.accountInformation(assetInfo.params.creator)
.do();
if (creatorAcctInfo["auth-addr"] === tbAddr) {
throw new Error("Cannot re-attest wormhole assets");
}
}
const result = await optin(
client,
senderAddr,
tokenBridgeId,
assetId,
textToHexString("native")
);
creatorAddr = result.addr;
txs.push(...result.txs);
const suggParams: SuggestedParams = await client.getTransactionParams().do();
const firstTxn = makeApplicationCallTxnFromObject({
from: senderAddr,
appIndex: safeBigIntToNumber(tokenBridgeId),
onComplete: OnApplicationComplete.NoOpOC,
appArgs: [textToUint8Array("nop")],
suggestedParams: suggParams,
});
txs.push({ tx: firstTxn, signer: null });
const mfee = await getMessageFee(client, bridgeId);
if (mfee > BigInt(0)) {
const feeTxn = makePaymentTxnWithSuggestedParamsFromObject({
from: senderAddr,
suggestedParams: suggParams,
to: getApplicationAddress(tokenBridgeId),
amount: mfee,
});
txs.push({ tx: feeTxn, signer: null });
}
let accts: string[] = [
emitterAddr,
creatorAddr,
getApplicationAddress(bridgeId),
];
if (creatorAcctInfo) {
accts.push(creatorAcctInfo["address"]);
}
let appTxn = makeApplicationCallTxnFromObject({
appArgs: [bPgmName, bigIntToBytes(assetId, 8)],
accounts: accts,
appIndex: safeBigIntToNumber(tokenBridgeId),
foreignApps: [safeBigIntToNumber(bridgeId)],
foreignAssets: [safeBigIntToNumber(assetId)],
from: senderAddr,
onComplete: OnApplicationComplete.NoOpOC,
suggestedParams: suggParams,
});
if (mfee > BigInt(0)) {
appTxn.fee *= 3;
} else {
appTxn.fee *= 2;
}
txs.push({ tx: appTxn, signer: null });
return txs;
}
export async function attestTokenFromNear(
provider: Provider,
coreBridge: string,
tokenBridge: string,
asset: string
): Promise<FunctionCallOptions[]> {
const options: FunctionCallOptions[] = [];
const messageFee = await callFunctionNear(
provider,
coreBridge,
"message_fee"
);
if (!getIsWrappedAssetNear(tokenBridge, asset)) {
const { isRegistered } = await hashAccount(provider, tokenBridge, asset);
if (!isRegistered) {
// The account has not been registered. The first user to attest a non-wormhole token pays for the space
options.push({
contractId: tokenBridge,
methodName: "register_account",
args: { account: asset },
gas: new BN("100000000000000"),
attachedDeposit: new BN("2000000000000000000000"), // 0.002 NEAR
});
}
}
options.push({
contractId: tokenBridge,
methodName: "attest_token",
args: { token: asset, message_fee: messageFee },
attachedDeposit: new BN("3000000000000000000000").add(new BN(messageFee)), // 0.003 NEAR
gas: new BN("100000000000000"),
});
return options;
}
export async function attestNearFromNear(
provider: Provider,
coreBridge: string,
tokenBridge: string
): Promise<FunctionCallOptions> {
const messageFee =
(await callFunctionNear(provider, coreBridge, "message_fee")) + 1;
return {
contractId: tokenBridge,
methodName: "attest_near",
args: { message_fee: messageFee },
attachedDeposit: new BN(messageFee),
gas: new BN("100000000000000"),
};
}
/**
* Attest given token from Aptos.
* @param tokenBridgeAddress Address of token bridge
* @param tokenChain Origin chain ID
* @param tokenAddress Address of token on origin chain
* @returns Transaction payload
*/
export function attestFromAptos(
tokenBridgeAddress: string,
tokenChain: ChainId,
tokenAddress: string
): Types.EntryFunctionPayload {
return attestTokenAptos(tokenBridgeAddress, tokenChain, tokenAddress);
}
export async function attestFromSui(
provider: JsonRpcProvider,
coreBridgeStateObjectId: string,
tokenBridgeStateObjectId: string,
coinType: string,
feeAmount: BigInt = BigInt(0)
): Promise<TransactionBlock> {
const metadata = await provider.getCoinMetadata({ coinType });
if (metadata === null || metadata.id === null) {
throw new Error(`Coin metadata ID for type ${coinType} not found`);
}
const [coreBridgePackageId, tokenBridgePackageId] = await Promise.all([
getPackageId(provider, coreBridgeStateObjectId),
getPackageId(provider, tokenBridgeStateObjectId),
]);
const tx = new TransactionBlock();
const [feeCoin] = tx.splitCoins(tx.gas, [tx.pure(feeAmount)]);
const [messageTicket] = tx.moveCall({
target: `${tokenBridgePackageId}::attest_token::attest_token`,
arguments: [
tx.object(tokenBridgeStateObjectId),
tx.object(metadata.id),
tx.pure(createNonce().readUInt32LE()),
],
typeArguments: [coinType],
});
tx.moveCall({
target: `${coreBridgePackageId}::publish_message::publish_message`,
arguments: [
tx.object(coreBridgeStateObjectId),
feeCoin,
messageTicket,
tx.object(SUI_CLOCK_OBJECT_ID),
],
});
return tx;
}