-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathstarknet.ts
More file actions
188 lines (161 loc) · 6.4 KB
/
starknet.ts
File metadata and controls
188 lines (161 loc) · 6.4 KB
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
/**
* Copyright 2025 Circle Internet Group, Inc. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { RpcProvider, Contract, Account, CallData, CairoByteArray } from "starknet";
import {
NODE_URL,
ACCOUNT_ADDRESS,
PRIVATE_KEY,
MESSAGE_TRANSMITTER_ADDRESS,
TOKEN_MESSENGER_MINTER_ADDRESS,
BURN_TOKEN_ADDRESS,
REMOTE_EVM_ADDRESS,
REMOTE_EVM_DOMAIN,
DESTINATION_CALLER,
} from "./config";
// Initialize provider and account
async function initializeAccount(nodeUrl: string, address: string, privateKey: string) {
const provider = new RpcProvider({ nodeUrl });
return new Account({
provider,
address,
signer: privateKey,
});
}
// Initialize contract with ABI
async function initializeContract(provider: RpcProvider, contractAddress: string) {
const { abi } = await provider.getClassAt(contractAddress);
if (!abi) {
throw new Error(`Failed to retrieve ABI for contract: ${contractAddress}`);
}
return new Contract({
abi,
address: contractAddress,
providerOrAccount: provider,
});
}
// Prepare message data for the contract call
function prepareMessageData(messageHex: string, attestationHex: string): any[] {
try {
const messageBytes = new CairoByteArray(messageHex);
const attestationBytes = new CairoByteArray(attestationHex);
return CallData.compile([...messageBytes.toApiRequest(), ...attestationBytes.toApiRequest()]);
} catch (error) {
throw new Error(`Failed to prepare message data: ${error}`);
}
}
async function getContracts() {
const usdcAddress = BURN_TOKEN_ADDRESS;
// Initialize provider
const provider = new RpcProvider({ nodeUrl: NODE_URL });
// Initialize account
const account = await initializeAccount(NODE_URL, ACCOUNT_ADDRESS!, PRIVATE_KEY!);
// Initialize contract
const messageTransmitter = await initializeContract(provider, MESSAGE_TRANSMITTER_ADDRESS);
const tokenMessengerMinter = await initializeContract(provider, TOKEN_MESSENGER_MINTER_ADDRESS!);
const usdcContract = await initializeContract(provider, usdcAddress!);
// Connect account to contract
messageTransmitter.providerOrAccount = account;
tokenMessengerMinter.providerOrAccount = account;
usdcContract.providerOrAccount = account;
return { messageTransmitter, tokenMessengerMinter, usdcContract, provider };
}
export async function receiveMessage(messageHex: string, attestationHex: string) {
try {
const { messageTransmitter, provider } = await getContracts();
// Prepare call data
const callData = prepareMessageData(messageHex, attestationHex);
console.log("Initiating receive message transaction...");
// Execute receive message transaction
const receiveMessageTx = await messageTransmitter.receive_message(callData);
console.log(`Transaction submitted: ${receiveMessageTx.transaction_hash}`);
// Wait for transaction confirmation
const receipt = await provider.waitForTransaction(receiveMessageTx.transaction_hash);
if (!receipt.isSuccess()) {
throw new Error(
`Receive message transaction failed, Transaction hash: ${receiveMessageTx.transaction_hash}, Error: ${receipt.value}`,
);
}
console.debug("Receive receipt:", receipt);
return receiveMessageTx.transaction_hash;
} catch (error) {
console.error("Error in receiveMessage:", error);
process.exit(1);
}
}
async function approve(provider: RpcProvider, usdcContract: Contract, amount: number, address: string) {
console.log("Approving USDC spend on Starknet...");
const approveTx = await usdcContract.approve(address, amount);
const approveTxReceipt = await provider.waitForTransaction(approveTx.transaction_hash);
if (!approveTxReceipt.isSuccess()) {
throw new Error(
`Approve transaction failed, Transaction hash: ${approveTx.transaction_hash}, Error: ${approveTxReceipt.value}`,
);
}
console.log("Approved receipt:", approveTxReceipt.transaction_hash);
}
// Sanitize and normalize transaction hash to 32 bytes with leading zeros
const sanitizeTransactionHash = (txHash: string): string => {
const hash = txHash.trim().toLowerCase();
if (hash.length < 66) {
return `0x${hash.replace("0x", "").padStart(64, "0")}`;
}
return hash;
};
export async function depositForBurn(amount: number, maxFee: number, minFinalityThreshold: number, hookData?: string) {
try {
const { tokenMessengerMinter, usdcContract, provider } = await getContracts();
// Approve USDC spend
await approve(provider, usdcContract, amount, TOKEN_MESSENGER_MINTER_ADDRESS!);
console.log("Initiating deposit for burn transaction...");
// Execute deposit for burn transaction
const depositTx = hookData
? await tokenMessengerMinter.invoke("deposit_for_burn_with_hook", [
amount,
REMOTE_EVM_DOMAIN,
REMOTE_EVM_ADDRESS,
BURN_TOKEN_ADDRESS,
DESTINATION_CALLER,
maxFee,
minFinalityThreshold,
hookData,
])
: await tokenMessengerMinter.invoke("deposit_for_burn", [
amount,
REMOTE_EVM_DOMAIN,
REMOTE_EVM_ADDRESS,
BURN_TOKEN_ADDRESS,
DESTINATION_CALLER,
maxFee,
minFinalityThreshold,
]);
console.log(`Transaction submitted: ${depositTx.transaction_hash}`);
// Wait for transaction confirmation
const receipt = await provider.waitForTransaction(depositTx.transaction_hash);
if (!receipt.isSuccess()) {
throw new Error(
`Deposit transaction failed, Transaction hash: ${depositTx.transaction_hash}, Error: ${receipt.value}`,
);
}
console.debug("Deposit receipt:", receipt);
// starknet transaction hash is 64 characters long, we need to sanitize and normalize it to 32 bytes with leading zeros
return sanitizeTransactionHash(depositTx.transaction_hash);
} catch (error) {
console.error("Error in depositForBurn:", error);
process.exit(1);
}
}