11import  {  stringify  }  from  '@bitauth/libauth' ; 
2- import  {  Contract ,  ElectrumNetworkProvider  }  from  'cashscript' ; 
2+ import  {  Contract ,  ElectrumNetworkProvider ,   Output ,   TransactionBuilder  }  from  'cashscript' ; 
33import  {  compileFile  }  from  'cashc' ; 
44import  {  URL  }  from  'url' ; 
55
@@ -15,21 +15,44 @@ const provider = new ElectrumNetworkProvider('chipnet');
1515// Instantiate a new contract using the compiled artifact and network provider 
1616// AND providing the constructor parameters: 
1717// (recipient: alicePkh, funder: bobPkh, pledge: 10000) 
18- const  contract  =  new  Contract ( artifact ,  [ alicePkh ,  bobPkh ,  10000n ] ,  {  provider } ) ; 
18+ const  pledgeAmount  =  10_000n ; 
19+ const  contract  =  new  Contract ( artifact ,  [ alicePkh ,  bobPkh ,  pledgeAmount ] ,  {  provider } ) ; 
1920
2021// Get contract balance & output address + balance 
2122console . log ( 'contract address:' ,  contract . address ) ; 
23+ const  contractUtxos  =  await  contract . getUtxos ( ) ; 
24+ console . log ( 'contract utxos:' ,  contractUtxos ) ; 
2225console . log ( 'contract balance:' ,  await  contract . getBalance ( ) ) ; 
2326console . log ( 'contract opcount:' ,  contract . opcount ) ; 
2427console . log ( 'contract bytesize:' ,  contract . bytesize ) ; 
2528
29+ // Select a contract UTXO to spend from 
30+ const  contractInputUtxo  =  contractUtxos . find ( utxo  =>  utxo . satoshis  >  10_000n ) ; 
31+ if  ( ! contractInputUtxo )  throw  new  Error ( 'No contract UTXO with enough satoshis found' ) ; 
32+ const  inputAmount  =  contractInputUtxo . satoshis ; 
33+ 
34+ const  receiverOutput : Output  =  { 
35+   amount : 10_000n , 
36+   to : aliceAddress , 
37+ } ; 
38+ 
39+ // Construct the changeOutput 
40+ const  minerFee  =  1000n ; 
41+ const  changeAmount  =  inputAmount  -  pledgeAmount  -  minerFee ; 
42+ const  contractChangeOutput : Output  =  { 
43+   amount : changeAmount , 
44+   to : contract . address , 
45+ } ; 
46+ 
2647// Call the transfer function with any signature 
2748// Will send one pledge amount to alice, and send change back to the contract 
2849// Manually set fee to 1000 because this is hardcoded in the contract 
29- const  tx  =  await  contract . functions 
30-   . receive ( ) 
31-   . to ( aliceAddress ,  10000n ) 
32-   . withHardcodedFee ( 1000n ) 
33-   . send ( ) ; 
50+ const  transactionBuilder  =  new  TransactionBuilder ( {  provider } ) ; 
51+ 
52+ transactionBuilder . addInput ( contractInputUtxo ,  contract . unlock . receive ( ) ) ; 
53+ transactionBuilder . addOutput ( receiverOutput ) ; 
54+ if  ( changeAmount  >  pledgeAmount  +  minerFee )  transactionBuilder . addOutput ( contractChangeOutput ) ; 
55+ 
56+ const  tx  =  await  transactionBuilder . send ( ) ; 
3457
3558console . log ( 'transaction details:' ,  stringify ( tx ) ) ; 
0 commit comments