Skip to content
This repository has been archived by the owner on Feb 26, 2024. It is now read-only.

Commit

Permalink
Rename truffle-contract to @truffle/contract
Browse files Browse the repository at this point in the history
  • Loading branch information
eggplantzzz committed Aug 30, 2019
1 parent 4c80542 commit ebc5af5
Show file tree
Hide file tree
Showing 63 changed files with 184 additions and 126 deletions.
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,5 @@ packages/truffle/dependencies
# @truffle/debugger
packages/debugger/.tmp

# truffle-contract
packages/truffle-contract/dist
# @truffle/contract
packages/contract/dist
2 changes: 1 addition & 1 deletion packages/artifactor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ artifactor.save({/*...*/}); // => a promise saving MyContract.json to a given de
* Packages up build artifacts into `.json` files, which can then be included in your project with a simple `require`.
* Manages library addresses for linked libraries.

The artifactor can be used with [truffle-contract](https://github.com/trufflesuite/truffle/tree/develop/packages/truffle-contract), which provides features above and beyond `web3`:
The artifactor can be used with [@truffle/contract](https://github.com/trufflesuite/truffle/tree/develop/packages/contract), which provides features above and beyond `web3`:

* Synchronized transactions for better control flow: transactions won't be considered finished until you're guaranteed they've been mined.
* Promises. No more callback hell. Works well with `ES6` and `async/await`.
Expand Down
2 changes: 1 addition & 1 deletion packages/artifactor/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"mocha": "5.2.0",
"require-nocache": "^1.0.0",
"temp": "^0.8.3",
"truffle-contract": "^4.0.31",
"@truffle/contract": "^4.0.31",
"web3": "1.2.1"
},
"publishConfig": {
Expand Down
2 changes: 1 addition & 1 deletion packages/artifactor/test/contracts.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const assert = require("chai").assert;
const Artifactor = require("../");
const contract = require("truffle-contract");
const contract = require("@truffle/contract");
const Schema = require("@truffle/contract-schema");
const temp = require("temp").track();
const path = require("path");
Expand Down
2 changes: 1 addition & 1 deletion packages/artifactor/test/customoptions.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const assert = require("chai").assert;
const Artifactor = require("../");
const temp = require("temp").track();
const contract = require("truffle-contract");
const contract = require("@truffle/contract");
const path = require("path");
const requireNoCache = require("require-nocache")(module);

Expand Down
2 changes: 1 addition & 1 deletion packages/artifactor/test/networksave.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const assert = require("chai").assert;
const Artifactor = require("../");
const temp = require("temp").track();
const contract = require("truffle-contract");
const contract = require("@truffle/contract");
const path = require("path");
const fs = require("fs");
const requireNoCache = require("require-nocache")(module);
Expand Down
4 changes: 2 additions & 2 deletions packages/contract-schema/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
| JSON Schema | [contract-object.spec.json](spec/contract-object.spec.json) |


[truffle-contract](https://github.com/trufflesuite/truffle/tree/develop/packages/truffle-contract) uses a
[@truffle/contract](https://github.com/trufflesuite/truffle/tree/develop/packages/contract) uses a
formally specified<sup>[1](#footnote-1)</sup> JSON object format to represent
Ethereum Virtual Machine (EVM) smart contracts. This representation is intended
to facilitate the use of general purpose smart contract abstractions
(such as truffle-contract) by capturing relevant smart contract information in a
(such as @truffle/contract) by capturing relevant smart contract information in a
persistent and portable manner.

Objects following this schema represent individual smart contracts as defined
Expand Down
2 changes: 1 addition & 1 deletion packages/contract-schema/test/networks.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
var contract = require("truffle-contract");
var contract = require("@truffle/contract");

var Schema = require("../index.js");
var assert = require("assert");
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
26 changes: 13 additions & 13 deletions packages/truffle-contract/README.md → packages/contract/README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
# truffle-contract
# @truffle/contract

Better Ethereum contract abstraction, for Node and the browser.

### Install

```
$ npm install truffle-contract
$ npm install @truffle/contract
```

### Features
Expand All @@ -17,11 +17,11 @@ $ npm install truffle-contract

### Usage

First, set up a new web3 provider instance and initialize your contract, then `require("truffle-contract")`. The input to the `contract` function is a JSON blob defined by [@truffle/contract-schema](https://github.com/trufflesuite/truffle/tree/master/packages/contract-schema). This JSON blob is structured in a way that can be passed to all truffle-related projects.
First, set up a new web3 provider instance and initialize your contract, then `require("@truffle/contract")`. The input to the `contract` function is a JSON blob defined by [@truffle/contract-schema](https://github.com/trufflesuite/truffle/tree/master/packages/contract-schema). This JSON blob is structured in a way that can be passed to all truffle-related projects.

```javascript
var provider = new Web3.providers.HttpProvider("http://localhost:8545");
var contract = require("truffle-contract");
var contract = require("@truffle/contract");

var MyContract = contract({
abi: ...,
Expand Down Expand Up @@ -59,26 +59,26 @@ or equivalently in ES6 <sup>(node.js 8 or newer)</sup>:

### Browser Usage

In your `head` element, include truffle-contract:
In your `head` element, include @truffle/contract:

```
<script type="text/javascript" src="./dist/truffle-contract.min.js"></script>
```

Alternatively, you can use the non-minified versions for easier debugging.

With this usage, `truffle-contract` will be available via the `TruffleContract` object:
With this usage, `@truffle/contract` will be available via the `TruffleContract` object:

```
var MyContract = TruffleContract(...);
```

**Note**: Web3 and its dependencies are now bundled into truffle-contract
**Note**: Web3 and its dependencies are now bundled into @truffle/contract
v4.0.2 or higher.

### Full Example

Let's use `truffle-contract` with an example contract from [Dapps For Beginners](https://dappsforbeginners.wordpress.com/tutorials/your-first-dapp/). In this case, the abstraction has been saved to a `.sol` file by [@truffle/artifactor](https://github.com/trufflesuite/truffle/tree/master/packages/artifactor):
Let's use `@truffle/contract` with an example contract from [Dapps For Beginners](https://dappsforbeginners.wordpress.com/tutorials/your-first-dapp/). In this case, the abstraction has been saved to a `.sol` file by [@truffle/artifactor](https://github.com/trufflesuite/truffle/tree/master/packages/artifactor):

```javascript
// Require the package that was previosly saved by @truffle/artifactor
Expand All @@ -88,7 +88,7 @@ var MetaCoin = require("./path/to/MetaCoin.sol");
MetaCoin.setProvider(provider);

// In this scenario, two users will send MetaCoin back and forth, showing
// how truffle-contract allows for easy control flow.
// how @truffle/contract allows for easy control flow.
var account_one = "5b42bd01ff...";
var account_two = "e1fd0d4a52...";

Expand All @@ -103,9 +103,9 @@ MetaCoin.at(contract_address).then(function(instance) {
// to the account listed as account_two.
return coin.sendCoin(account_two, 3, {from: account_one});
}).then(function(result) {
// This code block will not be executed until truffle-contract has verified
// This code block will not be executed until @truffle/contract has verified
// the transaction has been processed and it is included in a mined block.
// truffle-contract will error if the transaction hasn't been processed in 120 seconds.
// @truffle/contract will error if the transaction hasn't been processed in 120 seconds.

// Since we're using promises, we can return a promise for a call that will
// check account two's balance.
Expand Down Expand Up @@ -146,7 +146,7 @@ This function creates a new instance of the contract abstraction representing th

#### `MyContract.deployed()`

Creates an instance of the contract abstraction representing the contract at its deployed address. The deployed address is a special value given to truffle-contract that, when set, saves the address internally so that the deployed address can be inferred from the given Ethereum network being used. This allows you to write code referring to a specific deployed contract without having to manage those addresses yourself. Like `at()`, `deployed()` is thenable, and will resolve to a contract abstraction instance representing the deployed contract after ensuring that code exists at that location and that that address exists on the network being used.
Creates an instance of the contract abstraction representing the contract at its deployed address. The deployed address is a special value given to @truffle/contract that, when set, saves the address internally so that the deployed address can be inferred from the given Ethereum network being used. This allows you to write code referring to a specific deployed contract without having to manage those addresses yourself. Like `at()`, `deployed()` is thenable, and will resolve to a contract abstraction instance representing the deployed contract after ensuring that code exists at that location and that that address exists on the network being used.

#### `MyContract.link(instance)`

Expand Down Expand Up @@ -304,7 +304,7 @@ instance.getValue.call().then(function(val) {
});
```

Even more helpful, however is we *don't even need* to use `.call` when a function is marked as `view` or `pure`, because `truffle-contract` will automatically know that that function can only be interacted with via a call:
Even more helpful, however is we *don't even need* to use `.call` when a function is marked as `view` or `pure`, because `@truffle/contract` will automatically know that that function can only be interacted with via a call:

```javascript
instance.getValue().then(function(val) {
Expand Down
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,27 +1,25 @@
var Reason = require('./reason');
var handlers = require('./handlers');
var Reason = require("./reason");
var handlers = require("./handlers");

var override = {

timeoutMessage: 'not mined within', // Substring of timeout err fired by web3
defaultMaxBlocks: 50, // Max # of blocks web3 will wait for a tx
timeoutMessage: "not mined within", // Substring of timeout err fired by web3
defaultMaxBlocks: 50, // Max # of blocks web3 will wait for a tx
pollingInterval: 1000,

/**
* Attempts to extract receipt object from Web3 error message
* @param {Object} message web3 error
* @return {Object|undefined} receipt
*/
extractReceipt(message){
const hasReceipt = message &&
message.includes('{');
message.includes('}');
extractReceipt(message) {
const hasReceipt = message && message.includes("{");
message.includes("}");

if (hasReceipt){
const receiptString = '{' + message.split('{')[1].trim();
if (hasReceipt) {
const receiptString = "{" + message.split("{")[1].trim();
try {
return JSON.parse(receiptString);
} catch (err){
} catch (err) {
// ignore
}
}
Expand All @@ -36,23 +34,22 @@ var override = {
* @param {Object} context execution state
* @param {Object} err error
*/
start: async function(context, web3Error){
start: async function(context, web3Error) {
var constructor = this;
var blockNumber = null;
var currentBlock = override.defaultMaxBlocks;
var maxBlocks = constructor.timeoutBlocks;

var timedOut = web3Error.message && web3Error.message.includes(override.timeoutMessage);
var timedOut =
web3Error.message && web3Error.message.includes(override.timeoutMessage);
var shouldWait = maxBlocks > currentBlock;

// Reject after attempting to get reason string if we shouldn't be waiting.
if (!timedOut || !shouldWait){

if (!timedOut || !shouldWait) {
// We might have been routed here in web3 >= beta.34 by their own status check
// error. We want to extract the receipt, emit a receipt event
// and reject it ourselves.
var receipt = override.extractReceipt(web3Error.message);
if (receipt){
if (receipt) {
await handlers.receipt(context, receipt);
return;
}
Expand All @@ -69,27 +66,25 @@ var override = {
}

// This will run every block from now until contract.timeoutBlocks
var listener = function(pollID){
var self = this;
var listener = function(pollID) {
currentBlock++;

if (currentBlock > constructor.timeoutBlocks){
if (currentBlock > constructor.timeoutBlocks) {
clearInterval(pollID);
return;
}

constructor.web3.eth.getTransactionReceipt(context.transactionHash)
constructor.web3.eth
.getTransactionReceipt(context.transactionHash)
.then(result => {
if (!result) return;

(result.contractAddress)
result.contractAddress
? constructor
.at(result.contractAddress)
.then(context.promiEvent.resolve)
.catch(context.promiEvent.reject)

: constructor.promiEvent.resolve(result);

})
.catch(err => {
clearInterval(pollID);
Expand All @@ -100,15 +95,15 @@ var override = {
// Start polling
let currentPollingBlock = await constructor.web3.eth.getBlockNumber();

const pollID = setInterval(async() => {
const pollID = setInterval(async () => {
const newBlock = await constructor.web3.eth.getBlockNumber();

if(newBlock > currentPollingBlock){
if (newBlock > currentPollingBlock) {
currentPollingBlock = newBlock;
listener(pollID);
}
}, override.pollingInterval);
},
}
};

module.exports = override;
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,28 @@ const reason = {
* @param {Web3} web3 a helpful friend
* @return {String|Undefined} decoded reason string
*/
_extract: function(res, web3){
_extract: function(res, web3) {
if (!res || (!res.error && !res.result)) return;

const errorStringHash = '0x08c379a0';
const errorStringHash = "0x08c379a0";

const isObject = res && typeof res === 'object' && res.error && res.error.data;
const isString = res && typeof res === 'object' && typeof res.result === 'string';
const isObject =
res && typeof res === "object" && res.error && res.error.data;
const isString =
res && typeof res === "object" && typeof res.result === "string";

if (isObject) {
const data = res.error.data;
const hash = Object.keys(data)[0];

if (data[hash].return && data[hash].return.includes(errorStringHash)){
return web3.eth.abi.decodeParameter('string', data[hash].return.slice(10));
if (data[hash].return && data[hash].return.includes(errorStringHash)) {
return web3.eth.abi.decodeParameter(
"string",
data[hash].return.slice(10)
);
}

} else if (isString && res.result.includes(errorStringHash)){
return web3.eth.abi.decodeParameter('string', res.result.slice(10));
} else if (isString && res.result.includes(errorStringHash)) {
return web3.eth.abi.decodeParameter("string", res.result.slice(10));
}
},

Expand All @@ -35,12 +39,12 @@ const reason = {
* @param {Object} web3
* @return {String|Undefined}
*/
get: function(params, web3){
get: function(params, web3) {
const packet = {
jsonrpc: '2.0',
method: 'eth_call',
params: [params, 'latest'],
id: new Date().getTime(),
jsonrpc: "2.0",
method: "eth_call",
params: [params, "latest"],
id: new Date().getTime()
};

return new Promise(resolve => {
Expand All @@ -49,7 +53,7 @@ const reason = {
resolve(reasonString);
});
});
},
}
};

module.exports = reason;
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
{
"name": "truffle-contract",
"name": "@truffle/contract",
"description": "A better contract abstraction for Ethereum (formerly EtherPudding)",
"license": "MIT",
"author": "Tim Coulter <tim.coulter@consensys.net>",
"homepage": "https://github.com/trufflesuite/truffle/tree/master/packages/truffle-contract#readme",
"repository": "https://github.com/trufflesuite/truffle/tree/master/packages/truffle-contract",
"author": "Tim Coulter <tim@trufflesuite.com>",
"homepage": "https://github.com/trufflesuite/truffle/tree/master/packages/contract#readme",
"repository": "https://github.com/trufflesuite/truffle/tree/master/packages/contract",
"bugs": {
"url": "https://github.com/trufflesuite/truffle/issues"
},
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,15 @@ var assert = require("chai").assert;
var contract = require("../");

describe("Custom options", function() {

it("allows custom options", function() {
var Example = contract({
contractName: "Example",
abi: [],
binary: "0xabcdef",
address: "0xe6e1652a0397e078f434d6dda181b218cfd42e01",
network_id: 3,
"contractName": "Example",
"abi": [],
"binary": "0xabcdef",
"address": "0xe6e1652a0397e078f434d6dda181b218cfd42e01",
"network_id": 3,
"x-from-dependency": "somedep"
});
assert.equal(Example["x-from-dependency"], "somedep");
});

});
File renamed without changes.
Loading

0 comments on commit ebc5af5

Please sign in to comment.