This article summarizes the methods of using Solidity to create contracts within contracts and refer to other contracts in Ethereum smart contracts, including how to use mochai for testing.
Before that, understand a comparison:
Contract{}
Equivalent to classes in object-oriented languages- When obtained after deployment
address
,address
it is equivalent to an object ,address 0x.......
which itself is similar to a pointer address
Then we discuss the operation of contract classes and contract objects in Solidity code .
Solidity
First, distinguish the following three writing methods:
import 'ContractB.sol';
ConractB B = new ConractB(arg1,arg2...);
ContractB B = ContractB(Baddress);
function setContractB(ContractB b) public {
B = b;
}
The above pseudocode describes three ways to operate the contract in the contract:
The first paragraph new ContractB(arg1,arg2...)
is to directly create a new contract, just like you directly deploy a new contract, a new address and a new contract object will be generated.
The second paragraph ContractB B = ContractB(Baddress)
does not add new, which refers to other contracts that have been newed according to the address, and the method variables of the referenced contract can be used
The third paragraph is to directly pass in other contracts when executing the contract method to achieve the purpose of calling other contract methods in this contract. Of course, the general variable type is, that is to say, interface
we generally write methods like this: function setContractB(IContractB b) public
. Note the use IContractB
rather than ContractB
as a variable type, which is an interface, not a contract class. Of course you can still use the contract class directly as the type.
test
The new contract in the test code is:
const contract = ContractB.new(arg1, arg2, {
from:"0x...."})
The existing address reference contracts are:
const contract = new ContractB(address)
Ok, pay attention to the difference between solidity and js.