-
Notifications
You must be signed in to change notification settings - Fork 0
/
off-chain_code_unlock_funds
95 lines (74 loc) · 2.28 KB
/
off-chain_code_unlock_funds
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
import {
Blockfrost,
C,
Data,
Lucid,
SpendingValidator,
TxHash,
fromHex,
toHex,
} from "https://deno.land/x/[email protected]/mod.ts";
import * as cbor from "https://deno.land/x/[email protected]/index.js";
const lucid = await Lucid.new(
new Blockfrost(
"https://cardano-preview.blockfrost.io/api/v0",
Deno.env.get("BLOCKFROST_API_KEY"),
),
"Preview",
);
lucid.selectWalletFromPrivateKey(await Deno.readTextFile("./beneficiary.sk"));
const beneficiaryPublicKeyHash = lucid.utils.getAddressDetails(
await lucid.wallet.address()
).paymentCredential.hash;
const validator = await readValidator();
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 scriptAddress = lucid.utils.validatorToAddress(validator);
const scriptUtxos = await lucid.utxosAt(scriptAddress);
const Datum = Data.Object({
lock_until: Data.BigInt,
return_time: Data.BigInt,
owner: Data.String,
beneficiary: Data.String,
});
type Datum = Data.Static<typeof Datum>;
const currentTime = new Date().getTime();
const utxos = scriptUtxos.filter((utxo) => {
let datum = Data.from<Datum>(
utxo.datum,
Datum,
);
return datum.beneficiary === beneficiaryPublicKeyHash &&
datum.lock_until <= currentTime;
});
if (utxos.length === 0) {
console.log("No redeemable utxo found. You need to wait a little longer...");
Deno.exit(1);
}
const redeemer = Data.empty();
const txUnlock = await unlock(utxos, currentTime, { from: validator, using: redeemer });
await lucid.awaitTx(txUnlock);
console.log(`1 ADA recovered from the contract
Tx ID: ${txUnlock}
Redeemer: ${redeemer}
`);
async function unlock(utxos, currentTime, { from, using }): Promise<TxHash> {
const laterTime = new Date(currentTime + 2 * 60 * 60 * 1000).getTime(); // add two hours (TTL: time to live)
const tx = await lucid
.newTx()
.collectFrom(utxos, using)
.addSigner(await lucid.wallet.address())
.validFrom(currentTime)
.validTo(laterTime)
.attachSpendingValidator(from)
.complete();
const signedTx = await tx
.sign()
.complete();
return signedTx.submit();
}