-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathcircleBridge.ts
227 lines (194 loc) · 6.69 KB
/
circleBridge.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
import { Connection, PublicKey, Transaction } from '@solana/web3.js';
import {
AccountAddress,
ChainAddress,
ChainsConfig,
CircleBridge,
CircleTransferMessage,
Contracts,
Network,
Platform,
circle,
} from '@wormhole-foundation/connect-sdk';
import { BN, EventParser, Program } from '@project-serum/anchor';
import { getAssociatedTokenAddressSync } from '@solana/spl-token';
import {
SolanaAddress,
SolanaChains,
SolanaPlatform,
SolanaPlatformType,
SolanaTransaction,
SolanaUnsignedTransaction,
} from '@wormhole-foundation/connect-sdk-solana';
import { MessageTransmitter, TokenMessenger } from '.';
import {
createReadOnlyMessageTransmitterProgramInterface,
createReadOnlyTokenMessengerProgramInterface,
} from './utils';
import {
calculateFirstNonce,
createDepositForBurnInstruction,
createReceiveMessageInstruction,
nonceAccount,
} from './utils/instructions';
export class SolanaCircleBridge<N extends Network, C extends SolanaChains>
implements CircleBridge<N, SolanaPlatformType, C>
{
readonly tokenMessenger: Program<TokenMessenger>;
readonly messageTransmitter: Program<MessageTransmitter>;
private constructor(
readonly network: N,
readonly chain: C,
readonly connection: Connection,
readonly contracts: Contracts,
) {
if (network === 'Devnet')
throw new Error('CircleBridge not supported on Devnet');
const msgTransmitterAddress = contracts.cctp?.messageTransmitter;
if (!msgTransmitterAddress)
throw new Error(
`Circle Messenge Transmitter contract for domain ${chain} not found`,
);
this.messageTransmitter = createReadOnlyMessageTransmitterProgramInterface(
new PublicKey(msgTransmitterAddress),
this.connection,
);
const tokenMessengerAddress = contracts.cctp?.tokenMessenger;
if (!tokenMessengerAddress)
throw new Error(
`Circle Token Messenger contract for domain ${chain} not found`,
);
this.tokenMessenger = createReadOnlyTokenMessengerProgramInterface(
new PublicKey(tokenMessengerAddress),
this.connection,
);
}
static async fromRpc<N extends Network>(
provider: Connection,
config: ChainsConfig<N, Platform>,
): Promise<SolanaCircleBridge<N, SolanaChains>> {
const [network, chain] = await SolanaPlatform.chainFromRpc(provider);
const conf = config[chain]!;
if (conf.network !== network)
throw new Error(`Network mismatch: ${conf.network} != ${network}`);
return new SolanaCircleBridge(
network as N,
chain,
provider,
conf.contracts,
);
}
async *redeem(
sender: AccountAddress<C>,
message: CircleBridge.Message,
attestation: string,
): AsyncGenerator<SolanaUnsignedTransaction<N, C>> {
const usdc = new PublicKey(
circle.usdcContract.get(this.network, this.chain),
);
const senderPk = new SolanaAddress(sender).unwrap();
const ix = await createReceiveMessageInstruction(
this.messageTransmitter.programId,
this.tokenMessenger.programId,
usdc,
message,
attestation,
senderPk,
);
const transaction = new Transaction();
transaction.feePayer = senderPk;
transaction.add(ix);
yield this.createUnsignedTx({ transaction }, 'CircleBridge.Redeem');
}
async *transfer(
sender: AccountAddress<C>,
recipient: ChainAddress,
amount: bigint,
): AsyncGenerator<SolanaUnsignedTransaction<N, C>> {
const usdc = new PublicKey(
circle.usdcContract.get(this.network, this.chain),
);
const senderPk = new SolanaAddress(sender).unwrap();
const senderATA = getAssociatedTokenAddressSync(usdc, senderPk);
const destinationDomain = circle.circleChainId.get(recipient.chain);
const destinationAddress = recipient.address.toUniversalAddress();
const ix = await createDepositForBurnInstruction(
this.messageTransmitter.programId,
this.tokenMessenger.programId,
usdc,
destinationDomain,
senderPk,
senderATA,
destinationAddress,
amount,
);
const transaction = new Transaction();
transaction.feePayer = senderPk;
transaction.add(ix);
yield this.createUnsignedTx({ transaction }, 'CircleBridge.Transfer');
}
async isTransferCompleted(message: CircleBridge.Message): Promise<boolean> {
const usedNoncesAddress = nonceAccount(
message.nonce,
message.sourceDomain,
this.messageTransmitter.programId,
);
const firstNonce = calculateFirstNonce(message.nonce);
// usedNonces should be a [u64;100] where each bit is a nonce flag
const { usedNonces } =
// @ts-ignore --
await this.messageTransmitter.account.usedNonces.fetch(usedNoncesAddress);
// get the nonce index based on the account's first nonce
const nonceIndex = Number(message.nonce - firstNonce);
// get the the u64 the nonce's flag is in
const nonceElement = usedNonces[Math.floor(nonceIndex / 64)];
if (!nonceElement) throw new Error('Invalid nonce byte index');
// get the nonce flag index and build a bitmask
const nonceBitIndex = nonceIndex % 64;
const mask = new BN(1 << nonceBitIndex);
// If the flag is 0 it is _not_ used
return !nonceElement.and(mask).isZero();
}
// Fetch the transaction logs and parse the CircleTransferMessage
async parseTransactionDetails(txid: string): Promise<CircleTransferMessage> {
const tx = await this.connection.getTransaction(txid);
if (!tx || !tx.meta) throw new Error('Transaction not found');
// this log contains the cctp message information
const messageTransmitterParser = new EventParser(
this.messageTransmitter.programId,
this.messageTransmitter.coder,
);
const messageLogs = [
...messageTransmitterParser.parseLogs(tx.meta.logMessages || []),
];
const message = new Uint8Array(messageLogs[0].data['message'] as Buffer);
const [msg, hash] = CircleBridge.deserialize(message);
const { payload: body } = msg;
const xferSender = body.messageSender;
const xferReceiver = body.mintRecipient;
const sendChain = circle.toCircleChain(msg.sourceDomain);
const rcvChain = circle.toCircleChain(msg.destinationDomain);
const token = { chain: sendChain, address: body.burnToken };
return {
from: { chain: sendChain, address: xferSender },
to: { chain: rcvChain, address: xferReceiver },
token: token,
amount: body.amount,
message: msg,
id: { hash },
};
}
private createUnsignedTx(
txReq: SolanaTransaction,
description: string,
parallelizable: boolean = false,
): SolanaUnsignedTransaction<N, C> {
return new SolanaUnsignedTransaction(
txReq,
this.network,
this.chain,
description,
parallelizable,
);
}
}