forked from samrockcash/cashscript
-
Notifications
You must be signed in to change notification settings - Fork 1
/
p2pkh.ts
53 lines (42 loc) · 1.99 KB
/
p2pkh.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
import { BITBOX } from 'bitbox-sdk';
import { stringify } from '@bitauth/libauth';
import { Contract, SignatureTemplate, ElectrumNetworkProvider } from 'cashscript';
import { compileFile } from 'cashc';
import path from 'path';
run();
async function run(): Promise<void> {
// Initialise BITBOX
const bitbox = new BITBOX();
// Initialise HD node and alice's keypair
const rootSeed = bitbox.Mnemonic.toSeed('CashScript');
const hdNode = bitbox.HDNode.fromSeed(rootSeed);
const alice = bitbox.HDNode.toKeyPair(bitbox.HDNode.derive(hdNode, 0));
// Derive alice's public key and public key hash
const alicePk = bitbox.ECPair.toPublicKey(alice);
const alicePkh = bitbox.Crypto.hash160(alicePk);
// Compile the P2PKH contract to an artifact object
const artifact = compileFile(path.join(__dirname, 'p2pkh.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 (pkh: alicePkh)
const contract = new Contract(artifact, [alicePkh], provider);
// Get contract balance & output address + balance
console.log('contract address:', contract.address);
console.log('contract balance:', await contract.getBalance());
// Call the spend() function with alice's signature + pk
// And use it to send 0. 000 100 00 BCH back to the contract's address
const tx = await contract.functions
.spend(alicePk, new SignatureTemplate(alice))
.to(contract.address, 10000)
.send();
console.log('transaction details:', stringify(tx));
// Call the spend() function with alice's signature + pk
// And use it to send two outputs of 0. 000 150 00 BCH back to the contract's address
const tx2 = await contract.functions
.spend(alicePk, new SignatureTemplate(alice))
.to(contract.address, 15000)
.to(contract.address, 15000)
.send();
console.log('transaction details:', stringify(tx2));
}