@@ -27,14 +27,24 @@ function libraryHashPlaceholder (fullyQualifiedLibraryName) {
2727 *
2828 * @param address Address to replace placeholders with. Must be the right length.
2929 * It will **not** be padded with zeros if too short.
30+ *
31+ * @param linkReferences A optional mapping of libraries to lists of placeholder positions in the binary.
3032 */
31- function replacePlaceholder ( bytecode , label , address ) {
33+ function replacePlaceholder ( bytecode : string , label : string , address : string , linkReferences ?: LinkReferences ) : string {
34+ // Try to find link references if `linkReferences` is not provided
35+ if ( ! linkReferences ) {
36+ linkReferences = findLinkReferences ( bytecode ) ;
37+ }
38+
3239 // truncate to 36 characters
3340 const truncatedName = label . slice ( 0 , 36 ) ;
34- const libLabel = `__${ truncatedName . padEnd ( 36 , '_' ) } __` ;
3541
36- while ( bytecode . indexOf ( libLabel ) >= 0 ) {
37- bytecode = bytecode . replace ( libLabel , address ) ;
42+ if ( linkReferences && linkReferences [ truncatedName ] ) {
43+ linkReferences [ truncatedName ] . forEach ( function ( reference ) {
44+ const start = reference . start * 2 ;
45+ const end = ( reference . start + reference . length ) * 2 ;
46+ bytecode = bytecode . slice ( 0 , start ) + address + bytecode . slice ( end ) ;
47+ } ) ;
3848 }
3949
4050 return bytecode ;
@@ -55,10 +65,12 @@ function replacePlaceholder (bytecode, label, address) {
5565 * @param libraries Mapping between fully qualified library names and the hex-encoded
5666 * addresses they should be replaced with. Addresses shorter than 40 characters are automatically padded with zeros.
5767 *
68+ * @param linkReferences A optional mapping of libraries to lists of placeholder positions in the binary.
69+ *
5870 * @returns bytecode Hex-encoded bytecode string with placeholders replaced with addresses.
5971 * Note that some placeholders may remain in the bytecode if `libraries` does not provide addresses for all of them.
6072 */
61- function linkBytecode ( bytecode : string , libraries : LibraryAddresses ) : string {
73+ function linkBytecode ( bytecode : string , libraries : LibraryAddresses , linkReferences ?: LinkReferences ) : string {
6274 assert ( typeof bytecode === 'string' ) ;
6375 assert ( typeof libraries === 'object' ) ;
6476
@@ -103,8 +115,8 @@ function linkBytecode (bytecode: string, libraries: LibraryAddresses): string {
103115 // remove 0x prefix
104116 hexAddress = hexAddress . slice ( 2 ) . padStart ( 40 , '0' ) ;
105117
106- bytecode = replacePlaceholder ( bytecode , libraryName , hexAddress ) ;
107- bytecode = replacePlaceholder ( bytecode , libraryHashPlaceholder ( libraryName ) , hexAddress ) ;
118+ bytecode = replacePlaceholder ( bytecode , libraryName , hexAddress , linkReferences ) ;
119+ bytecode = replacePlaceholder ( bytecode , libraryHashPlaceholder ( libraryName ) , hexAddress , linkReferences ) ;
108120 }
109121
110122 return bytecode ;
0 commit comments