dethcrypto / typechain Goto Github PK
View Code? Open in Web Editor NEW๐ TypeScript bindings for Ethereum smart contracts
License: MIT License
๐ TypeScript bindings for Ethereum smart contracts
License: MIT License
While this works if you use the Deployer, it does not in tests where you want to use .new to setup beforeEach sets. We build a smart contract library and our migrations in this library are empty
We end up with methods like:
export async function deploy<Contract extends Truffle.Contract<any>>(
contract: Contract,
params: any[],
deployer?: Truffle.Deployer
) {
if (deployer) {
await deployer.deploy(
(contract as unknown) as Truffle.ContractNew<any[]>,
...params
);
return contract.deployed();
}
return ((contract as unknown) as Truffle.ContractNew<any[]>).new(...params);
}
For close to a year now Solidity also outputs the stateMutability
field for each function. This can have the following values:
For backwards compatibility also the field constant
(set to true on stateMutability
pure or view) and payable
(set to true on stateMutability
payable`) is present.
We'd like to phase out the constant
and payable
fields. For more see https://solidity.readthedocs.io/en/develop/abi-spec.html#json
It seems that abiParser.ts
doesn't support it: https://github.com/Neufund/TypeChain/blob/master/lib/abiParser.ts#L47
Truffle provides a way of calling a contract function in a way that returns the result as if the function call were to be executed against the current blockchain state, but without actually affecting the state. See here for documentation. The Truffle target doesn't currently provide typings for these.
With the following contract code:
uint number;
function setGetNumber(uint n) public returns (uint) {
number = n;
return number;
}
the following TypeScript should fail to compile:
const notANumber = [42]
const greeter = await Greeter.new("", { from: deployer });
await greeter.setGetNumber.call(notANumber)
but currently compiles.
With the following contract code:
function getNumber() public pure returns (uint) {
return 42;
}
the following TypeScript should successfully compile:
const greeter = await Greeter.new("", { from: deployer });
await greeter.getNumber.call()
but currently doesn't.
great project and works quite well with ethers v4
however, for a function declaration like function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes _data)
typechain for ethers generates the following declaration:
safeTransferFrom(
_from: string,
_to: string,
_id: number | string,
_amount: number | string,
_data: (string)[]
): Promise<ContractTransaction>;
the _data: (string)[]
argument is wrong, and should be: _data: Uint8Array
Hi, @krzkaczor.
Do you have plan add generation from .sol
file?
Right now I using such flow:
abi
from sol
file.typechain files' from
abi`.There is simplified cli script what I use for step 1.
#!/usr/bin/env node
const { execSync } = require('child_process');
const { readFileSync, writeFileSync } = require('fs');
const { compile } = require('solc');
//Looks like cli arguments
const contractFilePath = 'sol/file/path/should/be/here/';
const contractName = 'ContractNameFromSolFile';
const abiFilePath = 'abi/file/path/should/be/here/';
const contractFile = readFileSync(contractFilePath);
const solcInstance = compile(contractFile.toString());
writeFileSync(abiFilePath, solcInstance.contracts[contractName].interface);
console.log('ABI is compiled');
ABIs can contain functions that take as argument or return tuples (Solidity structs). Granted, I don't think these are yet accessible from web3, but in anticipation of future updates, it would be nice if the parser didn't choke on the following contract code:
struct Struct1 {
uint number;
}
struct Struct2 {
Struct1 s;
}
Struct2 public s;
Hello there guys i am in love with TypeChain and i decided to integrate it with my framework it is called @gapi and you can find more information about the whole namespace here:
https://github.com/Stradivario/gapi
Gapi-Ethereum module is part of this namespace and it can be found at this repository:
https://github.com/Stradivario/gapi-ethereum
The main idea behind this Framework is to provide Angular 2+ environment where you can write singleton typescript classes with Dependency Injection and many more features you can read about inside repo readme.It is using GraphQL this is where the name come from GraphQL API aka. GAPI :))
If you want to use generated contracts from TypeChain you need to import them as follows also ABI's from truffle compilation to get the contract address when it is deployed to network.
import { GapiModule } from '@gapi/core';
import { GapiEthereumModule } from '@gapi/ethereum';
// Raw TypeChain compiled contracts
import { Coin } from '../core/contracts/Coin';
import { CoinCrowdsale } from '../core/contracts/CoinCrowdsale';
// Raw json ABI's
const CoinCrowdsaleABI = require('../../../truffle-metacoin-example/build/contracts/CoinCrowdsale.json');
const CoinABI = require('../../../truffle-metacoin-example/build/contracts/Coin.json');
@GapiModule({
imports: [
GapiEthereumModule.forRoot({
port: process.env.ETHEREUM_PORT || 8545,
rpc: process.env.ETHEREUM_HOST || 'http://localhost',
contracts: [
{
contract: Coin,
abi: CoinABI
},
{
contract: CoinCrowdsale,
abi: CoinCrowdsaleABI
}
]
})
]
})
export class CoreModule { }
Regards,
Kristiyan Tachev
With the legacy
target for web3-0.2.x, bool
arguments in contract methods are passed through a .toString()
in the generated TS class, which results in the argument always being set to true
on the blockchain side.
Did not test with other targets.
contract TestContract {
bool public field;
event FieldSet(bool value);
function setField(bool _field) public {
field = _field;
emit FieldSet(field);
}
}
import { artifacts, contract, web3 } from './truffle-globals';
import { TestContract } from '@contracts/TestContract';
import { expect } from 'chai';
import { it } from 'mocha';
contract('TestContract', accounts => {
let testInstance: TestContract;
before(async () => {
const truffleDeployedContract = await artifacts
.require(TestContract.name)
.new({ from: accounts[0] });
testInstance = await TestContract.createAndValidate(
web3,
truffleDeployedContract.address,
);
});
it('tests setting the field', async () => {
expect(await testInstance.field).to.eq(false);
await testInstance.setFieldTx(true).send({ from: accounts[0] });
expect(await testInstance.field).to.eq(true);
});
it('tests unsetting the field', async () => {
expect(await testInstance.field).to.eq(true);
await testInstance.setFieldTx(false).send({ from: accounts[0] });
expect(await testInstance.field).to.eq(false);
});
});
Most important detail: during the second test the emitted event says value: true
, even though the method was called with false
:
Contract: TestContract
โ tests setting the field (68ms)
1) tests unsetting the field
Events emitted during test:
---------------------------
FieldSet(value: true)
---------------------------
1 passing (264ms)
1 failing
1) Contract: TestContract
tests unsetting the field:
AssertionError: expected true to equal false
+ expected - actual
-true
+false
at Object.<anonymous> (test/asdf.spec.ts:27:45)
at Generator.next (<anonymous>)
at fulfilled (test/asdf.spec.ts:4:58)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:182:7)
The _field.toString()
argument in TestContract.ts
.
When the .toString()
conversion is removed manually, the test passes as expected.
public setFieldTx(
_field: boolean
): TC.DeferredTransactionWrapper<TC.ITxParams> {
return new TC.DeferredTransactionWrapper<TC.ITxParams>(this, "setField", [
_field.toString()
]);
}
typechain 0.3.8
web3 0.20.7
ganache-cli 6.1.8
truffle 4.1.13
What do you think about implementing a switch that would allow the user to choose between RxJS Observables and Promises? It would make this lib a lot easier to use with Angular.
First of all, great initiative!
Unfortunately, due to unstability of web3, things get broken :(
For example,
web3.eth.contract(abi).at(address)
must now be web3.eth.Contract(abi, address);
.
The package.json says MIT, but there is no included license file.
Is that an oversight or the plan is to attach a different license to this repo?
With [email protected]
as target, generated types no longer support BigNumber
for the contracts. As an example, this is the typing generated with [email protected]
-- https://github.com/MARKETProtocol/types/blob/develop/types/MarketCollateralPool.ts#L178 and the below is generated using [email protected]
target which has string
instead of BigNumber
-- https://github.com/MARKETProtocol/types/blob/feature/upgrade-web3-1.0.0/types/MarketCollateralPool.d.ts#L44
BigNumber
might need some additional parsing while generating the types I guess. Would be really great if this can be supported soon. Thanks :)
with noUnusedParameters
compiler option enabled, I get the following error:
$ rm -rf dist && npx tsc -p .
build/ts_contracts/typechain-runtime.ts:98:42 - error TS6133: 'res2' is declared but its value is never read.
98 watchedEvent.stopWatching((err2, res2) => {
~~~~
Could you please rename the unused param to _res2
(or remove it)? I'd submit a PR, but the change is really small, so let's not waste time for bureaucracy :)
This is generated and the createToken function is relevant here:
export interface ERC20TokenFactoryInstance {
createToken(
_name: string | BigNumber,
_decimals: number | BigNumber | string,
txDetails?: Truffle.TransactionDetails
): Promise<void>;
gateKeeper(txDetails?: Truffle.TransactionDetails): Promise<string>;
CREATE_TOKEN_ROLE(txDetails?: Truffle.TransactionDetails): Promise<string>;
}
Truffle actually return something here after the TX has completed:
// result is an object with the following values:
//
// result.tx => transaction hash, string
// result.logs => array of decoded events that were triggered within this transaction
// result.receipt => transaction receipt object, which includes gas used
{
tx: "0x6cb0bbb6466b342ed7bc4a9816f1da8b92db1ccf197c3f91914fc2c721072ebd",
receipt: {
// The return value from web3.eth.getTransactionReceipt(hash)
// See https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethgettransactionreceipt
},
logs: [
{
address: "0x13274fe19c0178208bcbee397af8167a7be27f6f",
args: {
val: BigNumber(5),
},
blockHash: "0x2f0700b5d039c6ea7cdcca4309a175f97826322beb49aca891bf6ea82ce019e6",
blockNumber: 40,
event: "ValueSet",
logIndex: 0,
transactionHash: "0x6cb0bbb6466b342ed7bc4a9816f1da8b92db1ccf197c3f91914fc2c721072ebd",
transactionIndex: 0,
type:"mined",
},
],
}
This is just enough for my use case:
export interface ITruffleLog {
address: string;
args: any;
blockHash: string;
blockNumber: number;
event: string;
logIndex: number;
transactionHash: string;
transactionIndex: number;
type: string;
}
export interface ITruffleResponse {
tx: string;
receipt: any;
logs: ITruffleLog[];
}
send
methods in web3 target have incorrect return types.
Here is a failing test proving what's wrong: #129 Current return type is T (boolean in that case) where it should be a transaction object.
This could be an error in web3 typings, not necessary in Typechain but it will probably require some changes in typechain as well.
Currently different targets use totally different contracts during integration testing. We should create basic suite of smart contracts that will be tested across all different targets.
It should look something like web3/DumbContracts.sol. Things to test:
It would be great to have the possibility to specify one or more npm packages where typechain will look for abi's.
Until now, we have different projects for DAPP and contracts and include the abis as an npm package to make it easier to reference the contracts, instead of pointing outside the project. Makes it less a hassle when working with CI tools to just package the contracts and include them in node_modules. Its also more adaptable when on different systems/machines etc.
I am somehow not able to put an enhancement tag to this issue so please forgive me that.
I might implement these later, but for now it'd be useful to mention in the readme that constructors and fallbacks aren't supported yet ;) see here
When running
npm install --save-dev typechain
I get this
npm ERR! path myproj/node_modules/typechain/dist/cli.js
npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall chmod
npm ERR! enoent ENOENT: no such file or directory, chmod 'myproj/node_modules/typechain/dist/cli.js'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent
I think maybe cli.js didn't get included in the npm publish
As a developer, I'd like to see all the custom functions provided by TypeChain under the hood along with a sample code explaining their usage. One such example would be to watch for the events during a transaction.
I propose changes to generated code:
export default
instead of plain export
in generated classesweb3.eth.contract(contractAbi).at(address)
with new web3.eth.Contract(contractAbi, address)
in generated classesabi2wrapper(abi: Object, options: Object): string
that convert single ABI to TS wrapper class and will contain most of processFile()
's source code (calling generateSource
)Correct me if I'm wrong, but Iv'e not seen any code generated from events in the abi. Would be an awesome feature to have an rxjs.Observable
generated for each event.
Would be great to have a typesafe static deploy(..)
on each contract that would return a promise of an instance.
Add new target ethers.js
. Checklist:
Hello there,
I just installed latest typechain version globally and all of my build processes failed!
What is happening is that '--force' argument is deprecated.
Added some --target property for Truffle, web3, legacy
By now i was using legacy and now when i run it it says:
> typechain --target=legacy --outDir src/app/core/contracts './contracts/build/contracts/*.json'
Error occured: ENOENT: no such file or directory, open '/home/rampage/.nvm/versions/node/v8.9.4/lib/node_modules/typechain/dist/targets/legacy/runtime/typechain-runtime.ts'
I am sure this is not intended ?
So basically i don't have much time to waste and will downgrade typechain
to older version.
Please write some CHANGELOG or somewhere inside the REPO what is changed for example it is important if you decide to remove --force to write it somewhere.Thanks
Regards,
K.T.
Hi! I'm running into an issue with generating typings for JSON files.
My contract ABIs have the extension .json
rather than .abi
. From the README I think I should be using a glob pattern like typechain "build/contracts/*.json"
, but this doesn't find the files. If I rename the ABIs to the .abi
extension, the same glob works.
Not sure if I'm using this correctly or not!
Example:
contract Dispatcher is Upgradeable {
// no constructor
}
contract Upgradeable is Secured {
// no constructor
}
contract Secured is Converter {
constructor(address _gateKeeper) public {
gateKeeper = GateKeeper(_gateKeeper);
}
}
contract Converter {
// no constructor
}
This is the way to create a Dispatcher: Dispatcher.new(gateKeeper.address)
If you do not, the call will fail.
The typing however results in this, so passing an address gives an error
export interface DispatcherContract
extends Truffle.Contract<DispatcherInstance> {
"new"(meta?: Truffle.TransactionDetails): Promise<DispatcherInstance>;
}
Now, the contracts are not as clean and verbose as they can be (but they are valid).
I fixed it by adding constructor(address _gateKeeper) Upgradeable(_gateKeeper){}
to Dispatcher and constructor(address _gateKeeper) Secured(_gateKeeper){}
to Upgradeable. After which the typing is correct.
Hey there. How can i use typechain in angular 2+?
There currently is a @types/web3
now, and it seems to be getting more TLC than web3-typescript-typings. I don't use TypeChain currently, but I just so happened to notice this haha. I do want everyone to start using the same typings so that they can mature, and I believe DefinitelyTyped
is the right place for that.
Hi,
Awesome library by the way :)
I have this very weird error using truffle and a factory contract that creates other contracts. I've reproduced the error here: https://github.com/mrwillis/typechain-factory-repro. It is a very simple project.
Set up instructions are in the README.
For some reason, when I change the visibility of the problem
member in the created contract (Dummy.sol
) to public
, the transaction is unable to complete. I tried increasing the gas with ganache-cli
to a very large amount as well as the gas
setting in the truffle to no avail.
Any ideas? Is this a bug?
Thanks!
If you have a solidity contract which takes an argument of type bytes
, the typechain conversions will change the data you're sending in. The current definitions expect BigNumber[]
to be the passed in value for bytes
. When we convert that BigNumber array, it gets split out into a totally different format than what we input. For Examples:
contract TypeChainBugDemo {
// Calling this returns an unexpected value
function callWithBytes(bytes bytesArg) public returns (uint256){
return bytesArg.length;
}
}
This generates the following typescript
public callWithBytes(bytesArg: BigNumber[]): Promise<BigNumber> {
return promisify(this.rawWeb3Contract.callWithBytes, [bytesArg.map(val => val.toString())]);
}
As a caller, I assumed if I wanted to pass a bytes string of length 2, represented by the string "0xA20F"
, I would pass [new BigNumber('0xA2'), new BigNumber('0x0F')]
. Unfortunately, when this gets converted by typechain, it will change to ["162", "15"]. When that gets passed into web3, it actually cocatenates these strings, then gets their ASCII values for each character. Ultimately, the 2 byte input array gets expanded into a totally different 5 byte array.
I think the right fix is to have bytes always take in a string
for TypeChain. If you want the string to be interpreted as hex, it's just prepended with 0x and web3 takes care of things. Otherwise, web3 converts to utf-8 and passes in the byte stream for the string.
Here's plan for next couple of days (weeks?):
stateMutability
parameter: Releated: #65 I did some good progress here: https://github.com/krzkaczor/EthereumQL/tree/master/lib/parsere.g., contract.function.foo(arg1, arg2, { gasLimit: 5e6 })
does not correctly type
console.log("hi: ", (await helloWorld.sayHelloTx));
returns the function script entirely:
function sayHello() public returns(string)
"The returned string"
pragma solidity ^0.4.4;
contract HelloWorld {
function sayHello() public returns(string) {
return "hello";
}
}
console.log("hi: ", (await helloWorld.sayHelloTx));
By default it puts the output in the same folder as the ABI json. It would be nice to be able to specify a specific output directory.
I've configured truffle.js and tsconfig.json as described in the tutorial and installed all dependencies, but typechain still generates bindings only for first file found in the build directory.
I've tried to use truffle-typechain-example and put my contracts there, but I faced with the same error
If I have something like...
contract C {
struct Bar {
address foo;
uint256 baz;
}
function fun() returns (Bar) { ... }
}
Then the typing of C.functions.fun()
is Promise<object[]>;
.
When using the Web3 1.0.0 target, it seems that Typechain is generating incorrect types for bytes values.
The generated type is (string | number[])[]
, when I think it should be string | number[]
(no wrapping array). The generated type does not work with Web3.
Happy to try a PR if someone verifies this is indeed a bug ๐
It looks like in the generation code which creates a new DeferredTransactionWrapper
, all input arguments have their toString
method called on them. This works fine normally, but for array arguments the web3 formatting runtime gives an error trying to iterate over a string when it expects and array.
Given this Contract:
contract TypeChainBugDemo {
uint256 public _val;
// Calling this function from the generated TypeChain bindings will fail
function callWithArray(uint256[] arrayArg) public {
_val = arrayArg[0];
}
}
The callWithArray
function will generate the following TS definition:
public callWithArrayTx(
arrayArg: BigNumber[]
): DeferredTransactionWrapper<ITxParams> {
return new DeferredTransactionWrapper<ITxParams>(this, "callWithArray", [
arrayArg.toString()
]);
}
The line arrayArg.toString()
will convert our array into a single string. web3 eventually throws an error in SolidityType.prototype.encode
when it attempts to operate on that string thinking it's an array
TypeError: value.forEach is not a function
at /Users/sdesmond/GitHub/EVNT/truffle/node_modules/web3/lib/solidity/type.js:165:19
at SolidityTypeUInt.SolidityType.encode (/Users/sdesmond/GitHub/EVNT/truffle/node_modules/web3/lib/solidity/type.js:170:11)
at /Users/sdesmond/GitHub/EVNT/truffle/node_modules/web3/lib/solidity/coder.js:91:29
at Array.map (<anonymous>)
at SolidityCoder.encodeParams (/Users/sdesmond/GitHub/EVNT/truffle/node_modules/web3/lib/solidity/coder.js:90:34)
at SolidityFunction.toPayload (/Users/sdesmond/GitHub/EVNT/truffle/node_modules/web3/lib/web3/function.js:92:52)
at SolidityFunction.sendTransaction (/Users/sdesmond/GitHub/EVNT/truffle/node_modules/web3/lib/web3/function.js:163:24)
at /Users/sdesmond/GitHub/EVNT/truffle/gen-src/typechain-runtime.ts:58:9
A mapping of mapping would have a getter function with 2 parameters both named index
, which causes a conflict.
public example(
index: BigNumber | string,
index: BigNumber | number
): Promise<BigNumber> {
return promisify(this.rawWeb3Contract.example, [
index.toString(),
index.toString()
]);
}
So we use TypeChain and Truffle v5 heavily. Since v5 removed some output in migrations, I have to add them myself. After some discussion it appears I need to do this via the web3 1.0 ".on" PromiEvents: trufflesuite/truffle#1252 (comment) but these on methods are not typed.
The PromiEvents are typed nicely in @types/web3: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/web3/promiEvent.d.ts
(Note, Truffle 4 uses web3 0.2, Truffle 5 uses web 3 1.0, maybe you need a new target to keep BC)
What I think should fix this is moving from:
export interface EuroInstance extends Truffle.ContractInstance {
balanceOf(
_owner: string | BigNumber,
txDetails?: Truffle.TransactionDetails
): Promise<BigNumber>;
}
to
export interface EuroInstance extends Truffle.ContractInstance {
balanceOf(
_owner: string | BigNumber,
txDetails?: Truffle.TransactionDetails
): PromiEvent<BigNumber>;
}
We have in our contract library a GateKeeper contract which manages permissions for all contracts.
We have a typescript function to create permissions which looks like this currently:
export async function createPermission<ContractInstance>(
gateKeeper: GateKeeperContract,
securedContractInstance: ContractInstance,
permissionName: string,
permissionManagerAddress: string,
permissionRecipientAddress: string
) {
const deployedGateKeeper = await gateKeeper.deployed();
const role: string = await securedContractInstance[permissionName].call();
await deployedGateKeeper.createPermission(
permissionRecipientAddress,
(securedContractInstance as any).address,
role,
permissionManagerAddress
);
}
It would be much more clean if this could be:
export async function createPermission<ContractInstance extends Truffle.ContractInstance>(
gateKeeper: GateKeeperContract,
securedContractInstance: ContractInstance,
permissionName: string,
permissionManagerAddress: string,
permissionRecipientAddress: string
) {
const deployedGateKeeper = await gateKeeper.deployed();
const role: string = await securedContractInstance[permissionName].call();
await deployedGateKeeper.createPermission(
permissionRecipientAddress,
securedContractInstance.address,
role,
permissionManagerAddress
);
}
Apart from the address field, it would also allow us to be a lot more flexible in generics.
When the contract does not exist at the specified address the web3
instance from MetaMask will return 0x
and not 0x0
for the call to web3.eth.getCode
. So createAndValidate
does not throw an error. The check here checks for 0x0
.
I was not able to verify what the expected behaviour of web3
is. Will research another day.
The underlying implementation of a constant function invokes the web3 RPC to obtain the value. This is more than an idempotent operation and uses network resources / may block to obtain the reply.
Using getters sends the wrong message to the developers and the debugger:
Happy to submit a PR to correct this.
Result:
tsconfig with noUnusedLocals is not compiling because of IPayableTxParams and ITxParams are not used sometimes but they present inside the compiled source.
Expected:
ITxParams and IPayableTxParams to not present inside build
Really good work !! Thank you for this repository :)
Regards,
Kristiyan Tachev
I get the following error when trying to generate typings for an ABI:
Generating typings...
/usr/lib/node_modules/typechain/dist/abiParser.js:22
abi.forEach(function (abiPiece) {
^
TypeError: abi.forEach is not a function
at Object.parse (/usr/lib/node_modules/typechain/dist/abiParser.js:22:9)
at Object.generateSource (/usr/lib/node_modules/typechain/dist/generateSource.js:6:41)
at /usr/lib/node_modules/typechain/dist/cli.js:19:49
at Array.forEach (native)
at Object.<anonymous> (/usr/lib/node_modules/typechain/dist/cli.js:15:9)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
I am using Node version 8.2.1. Let me know if I can provide any further information ๐
Although web3 1.0.0 is still in beta it is now the default install candidate for npm so trying to use the default web3 with typechain doesn't work.
The specific problem seems to stem from a backwards incompatible API change they've made:
TypeError: web3.eth.contract is not a function
at new TypeChainContract (typechain-runtime.js:5)
Hi,
I have been trying to use Angular 5 interact with solidity contracts for a couple of weeks. It was a pin in my butt. Anyway, found out the article you posted in Dec last year and would like to give typechain a shot. However, I installed typechain following steps with this git post,
npm install --save-dev typechain
yarn add --dev typechain
and got "typechain: command not found" (ubuntu 16.04).
Your instruction also says that "you might need to make sure that it's available in your path if you installed it only locally". But how? ( Sorry, I am neither an JS stack nor a ubuntu expert) I could not find typescript command anywhere in the system.
Please help! This is my last attempt to salvage my Angular Blockchain project. Otherwise I would switch to React framework which is a way simpler to communicate with solidity contracts.
Thanks for your help in advance!
Calibre
@krzkaczor Hello there and again thank you for the great tool! Many thanks!
I am having the following case:
import { Module, ModuleWithServices } from '@gapi/core';
import { Web3Token } from '@gapi/ethereum';
import { Coin } from '../core/contracts/Coin';
import { CoinCrowdsale } from '../core/contracts/CoinCrowdsale';
const CoinCrowdsaleABI = require('../../../truffle-metacoin-example/build/contracts/CoinCrowdsale.json');
const CoinABI = require('../../../truffle-metacoin-example/build/contracts/Coin.json');
@Module()
export class ContractsModule {
public static forRoot(): ModuleWithServices {
return {
module: ContractsModule,
services: [
{
provide: Coin,
deps: [Web3Token],
lazy: true,
useFactory: async (web3: Web3Token) => {
return await Coin.createAndValidate(web3, CoinABI.networks[Object.keys(CoinABI.networks)[0]].address);
}
},
{
provide: CoinCrowdsale,
deps: [Web3Token],
lazy: true,
useFactory: async (web3: Web3Token) => {
return await CoinCrowdsale.createAndValidate(web3, CoinCrowdsaleABI.networks[Object.keys(CoinCrowdsaleABI.networks)[0]].address);
}
}
]
};
}
}
Is there any way to make it like that ?
import { Module, ModuleWithServices } from '@gapi/core';
import { Web3Token } from '@gapi/ethereum';
import { Coin } from '../core/contracts/Coin';
import { CoinCrowdsale } from '../core/contracts/CoinCrowdsale';
@Module()
export class ContractsModule {
public static forRoot(): ModuleWithServices {
return {
module: ContractsModule,
services: [
{
provide: Coin,
deps: [Web3Token],
lazy: true,
useFactory: async (web3: Web3Token) => {
return await Coin.createAndValidate(web3, Coin.address);
}
},
{
provide: CoinCrowdsale,
deps: [Web3Token],
lazy: true,
useFactory: async (web3: Web3Token) => {
return await CoinCrowdsale.createAndValidate(web3, CoinCrowdsale.address);
}
}
]
};
}
}
My current proposal is just to add deployed contract address when generating contract so it can be useful.Or is there any other way to obtain the address of the deployed contract ?
Regards,
Kristiyan Tachev
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.