-
Notifications
You must be signed in to change notification settings - Fork 0
/
hello-world-unlock.ts
78 lines (61 loc) · 1.8 KB
/
hello-world-unlock.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
import {
Blockfrost,
C,
Constr,
Data,
Lucid,
SpendingValidator,
TxHash,
fromHex,
toHex,
utf8ToHex,
} from "https://deno.land/x/lucid@0.8.3/mod.ts";
import * as cbor from "https://deno.land/x/cbor@v1.4.1/index.js";
import { type OutRef } from "https://deno.land/x/lucid@0.10.7/mod.ts";
import { type Redeemer } from "https://deno.land/x/lucid@0.10.7/mod.ts";
const lucid = await Lucid.new(
new Blockfrost(
"https://cardano-preview.blockfrost.io/api/v0",
Deno.env.get("BLOCKFROST_PROJECT_ID")
),
"Preview"
);
lucid.selectWalletFromPrivateKey(await Deno.readTextFile("./me.sk"));
const validator = await readValidator();
// --- Supporting functions
async function readValidator(): Promise<SpendingValidator> {
const validator = JSON.parse(await Deno.readTextFile("plutus.json"))
.validators[0];
return {
type: "PlutusV2",
script: toHex(cbor.encode(fromHex(validator.compiledCode))),
};
}
const utxo: OutRef = { txHash: Deno.args[0], outputIndex: 0 };
const redeemer = Data.to(new Constr(0, [utf8ToHex("Hello, World!")]));
const txHash = await unlock(utxo, {
from: validator,
using: redeemer,
});
await lucid.awaitTx(txHash);
console.log(`1 tADA unlocked from the contract
Tx ID: ${txHash}
Redeemer: ${redeemer}
`);
// --- Supporting functions
async function unlock(
ref: OutRef,
{ from, using }: { from: SpendingValidator; using: Redeemer }
): Promise<TxHash> {
const [utxo] = await lucid.utxosByOutRef([ref]);
const tx = await lucid
.newTx()
.collectFrom([utxo], using)
.addSigner(await lucid.wallet.address())
.attachSpendingValidator(from)
.complete();
const signedTx = await tx
.sign()
.complete();
return signedTx.submit();
}