1- import { binToHex , hexToBin } from '@bitauth/libauth' ;
1+ import { binToHex , decodeTransaction , hexToBin , isHex } from '@bitauth/libauth' ;
22import { sha256 } from '@cashscript/utils' ;
33import { Utxo , Network } from '../interfaces.js' ;
44import NetworkProvider from './NetworkProvider.js' ;
@@ -10,6 +10,7 @@ const bobAddress = 'bchtest:qz6q5gqnxdldkr07xpls5474mmzmlesd6qnux4skuc';
1010const carolAddress = 'bchtest:qqsr7nqwe6rq5crj63gy5gdqchpnwmguusmr7tfmsj' ;
1111
1212export default class MockNetworkProvider implements NetworkProvider {
13+ // we use lockingBytecode as the key for utxoMap to make cashaddresses and tokenaddresses interchangeable
1314 private utxoMap : Record < string , Utxo [ ] > = { } ;
1415 private transactionMap : Record < string , string > = { } ;
1516 public network : Network = Network . MOCKNET ;
@@ -45,11 +46,54 @@ export default class MockNetworkProvider implements NetworkProvider {
4546
4647 const txid = binToHex ( sha256 ( sha256 ( transactionBin ) ) . reverse ( ) ) ;
4748 this . transactionMap [ txid ] = txHex ;
49+
50+ const decoded = decodeTransaction ( transactionBin ) ;
51+ if ( typeof decoded === 'string' ) {
52+ throw new Error ( `${ decoded } ` ) ;
53+ }
54+
55+ // remove (spend) UTXOs from the map
56+ for ( const input of decoded . inputs ) {
57+ for ( const address of Object . keys ( this . utxoMap ) ) {
58+ const utxos = this . utxoMap [ address ] ;
59+ const index = utxos . findIndex (
60+ ( utxo ) => utxo . txid === binToHex ( input . outpointTransactionHash ) && utxo . vout === input . outpointIndex
61+ ) ;
62+
63+ if ( index !== - 1 ) {
64+ // Remove the UTXO from the map
65+ utxos . splice ( index , 1 ) ;
66+ this . utxoMap [ address ] = utxos ;
67+ break ; // Exit loop after finding and removing the UTXO
68+ }
69+ if ( utxos . length === 0 ) {
70+ delete this . utxoMap [ address ] ; // Clean up empty address entries
71+ }
72+ }
73+ }
74+
75+ // add new UTXOs to the map
76+ for ( const [ index , output ] of decoded . outputs . entries ( ) ) {
77+ this . addUtxo ( binToHex ( output . lockingBytecode ) , {
78+ txid : txid ,
79+ vout : index ,
80+ satoshis : output . valueSatoshis ,
81+ token : output . token && {
82+ ...output . token ,
83+ category : binToHex ( output . token . category ) ,
84+ nft : output . token . nft && {
85+ ...output . token . nft ,
86+ commitment : binToHex ( output . token . nft . commitment ) ,
87+ } ,
88+ } ,
89+ } ) ;
90+ }
91+
4892 return txid ;
4993 }
5094
51- addUtxo ( address : string , utxo : Utxo ) : void {
52- const lockingBytecode = binToHex ( addressToLockScript ( address ) ) ;
95+ addUtxo ( addressOrLockingBytecode : string , utxo : Utxo ) : void {
96+ const lockingBytecode = isHex ( addressOrLockingBytecode ) ? addressOrLockingBytecode : binToHex ( addressToLockScript ( addressOrLockingBytecode ) ) ;
5397 if ( ! this . utxoMap [ lockingBytecode ] ) {
5498 this . utxoMap [ lockingBytecode ] = [ ] ;
5599 }
0 commit comments