Skip to main content

Tích hợp trình duyệt

Bây giờ chúng ta đã chạy máy chủ của mình, chúng ta cần giao diện người dùng giao diện người dùng để tương tác với nó.

Đối với tất cả các hoạt động, cách tiếp cận (như đã đề cập trước đó) giống nhau, đó là trước tiên nhận giao dịch chưa được ký từ máy chủ, ký vào trình duyệt và sau đó gửi giao dịch đã ký trực tiếp từ ví hoặc từ Endpoint gửi của máy chủ.

Vì vậy, về cơ bản, chúng ta chỉ có thao tác ký diễn ra bên ngoài mã phía máy chủ và hoạt động trong trình duyệt. Để thực hiện nó, chúng ta sử dụng Lib đa nền tảng Cardano và là một bản mẫu cho tất cả các hoạt động của chúng ta.

note

Toàn bộ mã liên quan đến hoạt động của trình duyệt có sẵn tại đây.

const signAndSubmitTx = async (api: WalletApi, txCborHex: string): Promise<string> => {

console.log('Unsigned transaction CBOR hex is ' + txCborHex);

// Parse the base tx into the serialization lib model.
const transaction = C.Transaction.from_bytes(fromHex(txCborHex));
const txWitnessses = transaction.witness_set();
const txVKeyWitnesses = txWitnessses.vkeys() ?? C.Vkeywitnesses.new();

// Get the user to sign the base tx in the browser via wallet.
const signedWitnessSet = C.TransactionWitnessSet.from_bytes(
fromHex(await api.signTx(toHex(transaction.to_bytes()), true))
);

// Extract the vkey witnesses from the signing witness.
const walletVkeyWitnesses = signedWitnessSet.vkeys(); // This won't actually be nullish (CIP 30).

// Combine the wallet vkey witnesses with any existing vkey witnesses.
for (let i = 0; i < walletVkeyWitnesses?.len() ?? 0; i++) {
txVKeyWitnesses.add(walletVkeyWitnesses.get(i));
}

// Overwrite the vkeys in the tx witnesses.
txWitnessses.set_vkeys(txVKeyWitnesses);

// Compose the final tx.
const finalTx = C.Transaction.new(transaction.body(), txWitnessses, transaction.auxiliary_data());

// Convert to cbor hex. You can submit this in the browser with ` api.submitTx()` or using the submit endpoint at backend.
const finalTxCbor = toHex(finalTx.to_bytes());
console.log('Final transaction CBOR is ' + finalTxCbor);
return finalTxCbor;
}

Trường hợp ở api trên được lấy đơn giản từ trình duyệt như vậy. Tạo một loại chẳng hạn như là hoàn toàn tùy chọn. constapi:WalletApi=awaitwindow.cardano[selectedWallet].enable(); WalletApi

Một phác thảo của toàn bộ quá trình này được đưa ra dưới đây (body việc xây dựng thực tế cho yêu cầu minh họa này add-ref-script có thể được nhìn thấy trong đoạn mã đã cho):

const {data} = await axios.post('http://localhost:8081/betref/add-ref-script', body)
const finalTxCbor = await signAndSubmitTx(api, data.urspTxBodyHex)
// txHash = await wallet.submitTx(finalTxCbor); // alternate
const {data: submitData} = await axios.post('http://localhost:8081/tx/submit', finalTxCbor, {
headers: {
'Content-Type': 'application/json' // was inferred in previous `post`
}
})
console.log(submitData)
note

Chúng ta đã kết thúc phần hướng dẫn! Hy vọng bạn sẽ thành công và thích bài hướng dẫn này 💙


Picture