attach方法在ether .js中做什么?



根据ethers.js文档:

合同。附件(addressOrName)⇒合同

返回一个新的附加到新地址的合同实例。这在以下情况下很有用一份合同有多个相似或相同的副本网络,您希望与他们中的每一个进行交互。

但是我真的不明白它的用法。有人能用更容易理解的方式解释一下吗?下面是一个的例子。附件在使用中发现在"折衷"CTF挑战级别(https://github.com/tinchoabbate/damn-vulnerable-defi/blob/v2.1.0/test/compromised/compromised.challenge.js)

this.oracle = await TrustfulOracleFactory.attach(
await (
await TrustfulOracleInitializerFactory.deploy(
sources,
['DVNFT', 'DVNFT', 'DVNFT'],
[INITIAL_NFT_PRICE, INITIAL_NFT_PRICE, INITIAL_NFT_PRICE]
)
).oracle()

这段代码到底在做什么,为什么需要attach方法?

谁能用更容易理解的方式解释一下?

Attach从一个已经部署的契约和一个现有的实例(重用相同的ABI和Signer)创建一个新的契约实例。

这很有用,例如,如果您在不同的区块链上部署了相同的合约,那么当用户更改到网络时,您不需要重新创建实例。

或者,如果您有一个合约工厂,在同一网络上多次部署相同的合约,而不是为每个合约创建一个实例,您可以从一个实例中创建它们,因此您不必经历指定ABI文件和签名者的麻烦。

这段代码到底在做什么,为什么需要attach方法?

我不是专家,我也不是100%确定这段代码是做什么的,因为我没有合同代码。然而,我可以推测如下:

// Returns value of calling the oracle() method of the new contract instance.
this.oracle = await TrustfulOracleFactory.attach(
// waits for the deployment to finish ( kinda redundat here ).
await (
// waits until the contract is deployed, this returns an address.
//   the values in .deploy(...) are values passed to the constructor of the contract.
await TrustfulOracleInitializerFactory.deploy(
sources,
['DVNFT', 'DVNFT', 'DVNFT'],
[INITIAL_NFT_PRICE, INITIAL_NFT_PRICE, INITIAL_NFT_PRICE]

// On the new returned instance, call method Oracle.
)).oracle()


//--------- Step by Step code --------------- 
// Deploys contract, returns address.
let newContractAddress = await TrustfulOracleInitializerFactory.deploy(
sources,
['DVNFT', 'DVNFT', 'DVNFT'],
[INITIAL_NFT_PRICE, INITIAL_NFT_PRICE, INITIAL_NFT_PRICE]
);
// Get instance from address and previusly created instance ( reuse of the same ABI as TrustfulOracleFactory )
let oracleInstance = await TrustfulOracleFactory.attach(newContractAddress);
// Calls oracle method.
this.oracle = await oracleInstance.oracle();