I am learning Solidity and writing a contract that uses a library. I'm using truffle for the project. When I try to test the contract I get the following error
Error: User contains unresolved libraries. You must deploy and link the following libraries before you can deploy a new version of User: IterableMapping
The code for the library is taken from iterable_mapping.sol and stored in IterableMapping.sol
The code of the contract looks like following and stored in User.sol
pragma solidity ^0.4.18;
import "./IterableMapping.sol";
contract User
{
event ItemInserted(bool replaced);
event ItemRemoved(bool success);
// Just a struct holding our data.
IterableMapping.itmap data;
// Insert something
function insert(uint k, uint v) public returns (uint size)
{
// Actually calls itmap_impl.insert, auto-supplying the first parameter for us.
bool replaced = IterableMapping.insert(data, k, v);
ItemInserted(replaced);
// We can still access members of the struct - but we should take care not to mess with them.
return data.size;
}
function remove(uint k) public returns (bool success)
{
success = IterableMapping.remove(data, k);
ItemRemoved(success);
}
// Computes the sum of all stored data.
function sum() public view returns (uint s)
{
for (var i = IterableMapping.iterate_start(data); IterableMapping.iterate_valid(data, i); i = IterableMapping.iterate_next(data, i))
{
var (, value) = IterableMapping.iterate_get(data, i);
s += value;
}
}
}
The test code is
const User = artifacts.require('User');
contract('User', (accounts) => {
it('should insert an item', () => {
return User.new({
from: accounts[0]
}).then(instance => {
return instance.insert.call(1, 1234, {from: accounts[0]});
}).then(result => {
assert.equal(result, 1);
});
});
});
I am aware in general the library code should be deployed before the contract using it and the linker at compilation is told to replace the __IterableMapping________
with the address of the deployed library. But in case of testing its not deploying the contract and I'm not sure when i do the User.new
if and how can I pass which address to use for library.
1_initial_migrations.js
1_initial_migrations.js
to contain the followingdeployer.deploy(IterableMapping).then(() => { deployer.deploy(User).then(() => { deployer.link(IterableMapping, User); }); });