forked from samrockcash/cashscript
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhodl_vault.ts
51 lines (40 loc) · 1.91 KB
/
hodl_vault.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
import { stringify } from '@bitauth/libauth';
import { BITBOX } from 'bitbox-sdk';
import { Contract, SignatureTemplate, ElectrumNetworkProvider } from 'cashscript';
import { compileFile } from 'cashc';
import path from 'path';
import { PriceOracle } from './PriceOracle';
run();
async function run(): Promise<void> {
// Initialise BITBOX
const bitbox = new BITBOX();
// Initialise HD node and owner's keypair
const rootSeed = bitbox.Mnemonic.toSeed('CashScript');
const hdNode = bitbox.HDNode.fromSeed(rootSeed);
const owner = bitbox.HDNode.toKeyPair(bitbox.HDNode.derive(hdNode, 0));
const ownerPk = bitbox.ECPair.toPublicKey(owner);
// Initialise price oracle with a keypair
const oracleKeypair = bitbox.HDNode.toKeyPair(bitbox.HDNode.derive(hdNode, 1));
const oraclePk = bitbox.ECPair.toPublicKey(oracleKeypair);
const oracle = new PriceOracle(oracleKeypair);
// Compile the HodlVault contract to an artifact object
const artifact = compileFile(path.join(__dirname, 'hodl_vault.cash'));
// Initialise a network provider for network operations on TESTNET
const provider = new ElectrumNetworkProvider('testnet');
// Instantiate a new contract using the compiled artifact and network provider
// AND providing the constructor parameters
const parameters = [ownerPk, oraclePk, 597000, 30000];
const contract = new Contract(artifact, parameters, provider);
// Get contract balance & output address + balance
console.log('contract address:', contract.address);
console.log('contract balance:', await contract.getBalance());
// Produce new oracle message and signature
const oracleMessage = oracle.createMessage(597000, 30000);
const oracleSignature = oracle.signMessage(oracleMessage);
// Spend from the vault
const tx = await contract.functions
.spend(new SignatureTemplate(owner), oracleSignature, oracleMessage)
.to(contract.address, 1000)
.send();
console.log(stringify(tx));
}