web3.eth.personal

The web3-eth-personal package allows you to interact with the Ethereum node's accounts.

주석

Many of these functions send sensitive information, like password. Never call these functions over a unsecured Websocket or HTTP provider, as your password will be sent in plain text!

var Personal = require('web3-eth-personal');

// "Personal.providers.givenProvider" will be set if in an Ethereum supported browser.
var personal = new Personal(Personal.givenProvider || 'ws://some.local-or-remote.node:8546');


// or using the web3 umbrella package

var Web3 = require('web3');
var web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546');

// -> web3.eth.personal

setProvider

web3.setProvider(myProvider)
web3.eth.setProvider(myProvider)
web3.shh.setProvider(myProvider)
web3.bzz.setProvider(myProvider)
...

해당 모듈의 web3 Provider를 변경 또는 설정 합니다. .. note:: web3.eth, web3.shh 등등과 같은 모든 하위 모듈에 대해 동일한 Provider가 설정됩니다. web3.bzz 는 분리된 provider가 예외적으로 적용됩니다.

매개변수(Parameters)

  1. Object - myProvider: :ref:Provider를 검증합니다. <web3-providers>.

반환값 (Return)

Boolean

예시 (예시 (Example))

var Web3 = require('web3');
var web3 = new Web3('http://localhost:8545');
// 또는
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));

// provider를 변경합니다.
web3.setProvider('ws://localhost:8546');

// 또는

web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:8546'));

// node.js 에서 IPC Provider를 사용합니다.
var net = require('net');
var web3 = new Web3('/Users/myuser/Library/Ethereum/geth.ipc', net); // mac os 의 경로

// 또는

var web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Ethereum/geth.ipc', net)); // mac os 경로
// 윈도우의 경로 : "\\\\.\\pipe\\geth.ipc"
// 리눅스의 경로: "/users/myuser/.ethereum/geth.ipc"

providers(프로바이더)

web3.providers
web3.eth.providers
web3.shh.providers
web3.bzz.providers
...

Object with the following providers:

  • Object - HttpProvider:http 프로바이더는 더이상 사용되지 않게 되었습니다. 이것은 구독에 사용할 수 없을 것 입니다.
  • Object - WebsocketProvider: 웹 소켓 프로바이더는 레거시 브라우저에 대한 표준입니다.
  • Object - IpcProvider: IPC 프로바이더는 로컬노드를 사용하는 nodejs Dapp에 대한 표준입니다. 가장 안전한 연결을 제공합니다.

예시 (예시 (Example))

var Web3 = require('web3');
// use the given Provider, e.g in Mist, or instantiate a new websocket provider
//
var web3 = new Web3(Web3.givenProvider || 'ws://remotenode.com:8546');
// or
var web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider('ws://remotenode.com:8546'));

// Using the IPC provider in node.js
var net = require('net');

var web3 = new Web3('/Users/myuser/Library/Ethereum/geth.ipc', net); // mac os path
// or
var web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Ethereum/geth.ipc', net)); // mac os path
// on windows the path is: "\\\\.\\pipe\\geth.ipc"
// on linux the path is: "/users/myuser/.ethereum/geth.ipc"

설정하기

// ====
// Http
// ====

var Web3HttpProvider = require('web3-providers-http');

var options = {
    keepAlive: true,
    withCredentials: false,
    timeout: 20000, // ms
    headers: [
        {
            name: 'Access-Control-Allow-Origin',
            value: '*'
        },
        {
            ...
        }
    ],
    agent: {
        http: http.Agent(...),
        baseUrl: ''
    }
};

var provider = new Web3HttpProvider('http://localhost:8545', options);

// ==========
// 웹소켓
// ==========

var Web3WsProvider = require('web3-providers-ws');

var options = {
    timeout: 30000, // ms

    // 크레덴셜을 url에 포함해서 사용할 수 있습니다 ex: ws://username:password@localhost:8546
    headers: {
      authorization: 'Basic username:password'
    },

    // 만약 결과값이 크다면 사용할 수 있습니다.
    clientConfig: {
      maxReceivedFrameSize: 100000000,   // bytes - default: 1MiB
      maxReceivedMessageSize: 100000000, // bytes - default: 8MiB
    },

    // 자동 재연결 활성화
    reconnect: {
        auto: true,
        delay: 5000, // ms
        maxAttempts: 5,
        onTimeout: false
    }
};

var ws = new Web3WsProvider('ws://localhost:8546', options);
HTTP 와 Websocket 프로바이더에 대한 정보를 더 얻으려면 밑에 링크를 참고할 수 있습니다.

givenProvider

web3.givenProvider
web3.eth.
web3.shh.givenProvider
web3.bzz.givenProvider
...

이더리움 호환 브라우저에서 web3.js 를 사용하면, 이 함수는 해당 브라우저의 네이티브 프로바이더를 반환합니다. 호환 브라우저가 아닐 경우, null 을 반환합니다.

반환값 (Returns)

Object: 설정된 givenProvider 또는 null.;

예시 (Example)


currentProvider

web3.currentProvider
web3.eth.currentProvider
web3.shh.currentProvider
web3.bzz.currentProvider
...

현재 provider 또는 null 을 반환합니다

반환값 (Returns)

Object: 현재 설정된 프로바이더 또는 null;

예시 (Example)


BatchRequest

new web3.BatchRequest()
new web3.eth.BatchRequest()
new web3.shh.BatchRequest()
new web3.bzz.BatchRequest()

없음

반환값 (Returns)

Object: 밑에 두 메소드로 이루어져 있습니다:

  • add(request): batch call에 요청 오브젝트를 추가합니다.
  • execute(): batch 요청을 실행합니다.

예시 (Example)

var contract = new web3.eth.Contract(abi, address);

var batch = new web3.BatchRequest();
batch.add(web3.eth.getBalance.request('0x0000000000000000000000000000000000000000', 'latest', callback));
batch.add(contract.methods.balance(address).call.request({from: '0x0000000000000000000000000000000000000000'}, callback2));
batch.execute();

extend

web3.extend(methods)
web3.eth.extend(methods)
web3.shh.extend(methods)
web3.bzz.extend(methods)
...

web3 모듈을 확장할 수 있게 합니다.

인자

  1. methods - Object: 메서드 배열이 있는 확장 개체에서는 개체를 아래와 같이 설명한다:
    • property - String: (optional) 모듈에 추가할 속성의 이름. 설정된 속성이 없는 경우 모듈에 직접 추가됨.
    • methods - Array: 메서드 설명 배열
      • name - String: 추가할 메서드의 이름.
      • call - String: RPC 메서드의 이름.
      • params - Number: (optional) 함수에 대한 파라미터의 갯수, 기본값은 0.
      • inputFormatter - Array: (optional) 입력 포맷터 함수 배열. 각 어레이 항목은 함수 매개 변수에 응답하므로 일부 매개 변수를 포맷하지 않으려면 대신 null 을 추가하세요.
      • outputFormatter - ``Function: (optional) 메서드의 출력을 포맷하는 데 사용할 수 있다.

반환값 (Returns)

Object: 확장 모듈을 반환합니다.

예시 (Example)

web3.extend({
    property: 'myModule',
    methods: [{
        name: 'getBalance',
        call: 'eth_getBalance',
        params: 2,
        inputFormatter: [web3.extend.formatters.inputAddressFormatter, web3.extend.formatters.inputDefaultBlockNumberFormatter],
        outputFormatter: web3.utils.hexToNumberString
    },{
        name: 'getGasPriceSuperFunction',
        call: 'eth_gasPriceSuper',
        params: 2,
        inputFormatter: [null, web3.utils.numberToHex]
    }]
});

web3.extend({
    methods: [{
        name: 'directCall',
        call: 'eth_callForFun',
    }]
});

console.log(web3);
> Web3 {
    myModule: {
        getBalance: function(){},
        getGasPriceSuperFunction: function(){}
    },
    directCall: function(){},
    eth: Eth {...},
    bzz: Bzz {...},
    ...
}


newAccount

web3.eth.personal.newAccount(password, [callback])

Creates a new account.

주석

Never call this function over a unsecured Websocket or HTTP provider, as your password will be send in plain text!

Parameters

  1. password - String: The password to encrypt this account with.

Returns

Promise returns String: The address of the newly created account.

Example

web3.eth.personal.newAccount('!@superpassword')
.then(console.log);
> '0x1234567891011121314151617181920212223456'

sign

web3.eth.personal.sign(dataToSign, address, password [, callback])

The sign method calculates an Ethereum specific signature with:

sign(keccak256("\x19Ethereum Signed Message:\n" + dataToSign.length + dataToSign)))

Adding a prefix to the message makes the calculated signature recognisable as an Ethereum specific signature.

If you have the original message and the signed message, you can discover the signing account address using web3.eth.personal.ecRecover (See example below)

주석

Sending your account password over an unsecured HTTP RPC connection is highly unsecure.

Parameters

  1. String - Data to sign. If String it will be converted using web3.utils.utf8ToHex.
  2. String - Address to sign data with.
  3. String - The password of the account to sign data with.
  4. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise returns String - The signature.

Example

web3.eth.personal.sign("Hello world", "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", "test password!")
.then(console.log);
> "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"

// the below is the same
web3.eth.personal.sign(web3.utils.utf8ToHex("Hello world"), "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", "test password!")
.then(console.log);
> "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"

// recover the signing account address using original message and signed message
web3.eth.personal.ecRecover("Hello world", "0x30755ed65396...etc...")
.then(console.log);
> "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe"

ecRecover

web3.eth.personal.ecRecover(dataThatWasSigned, signature [, callback])

Recovers the account that signed the data.

Parameters

  1. String - Data that was signed. If String it will be converted using web3.utils.utf8ToHex.
  2. String - The signature.
  3. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise returns String - The account.

Example

web3.eth.personal.ecRecover("Hello world", "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400").then(console.log);
> "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe"

signTransaction

web3.eth.personal.signTransaction(transaction, password [, callback])

Signs a transaction. This account needs to be unlocked.

주석

Sending your account password over an unsecured HTTP RPC connection is highly unsecure.

Parameters

  1. Object - The transaction data to sign web3.eth.sendTransaction() for more.
  2. String - The password of the from account, to sign the transaction with.
  3. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise returns Object - The RLP encoded transaction. The raw property can be used to send the transaction using web3.eth.sendSignedTransaction.

Example

web3.eth.signTransaction({
    from: "0xEB014f8c8B418Db6b45774c326A0E64C78914dC0",
    gasPrice: "20000000000",
    gas: "21000",
    to: '0x3535353535353535353535353535353535353535',
    value: "1000000000000000000",
    data: ""
}, 'MyPassword!').then(console.log);
> {
    raw: '0xf86c808504a817c800825208943535353535353535353535353535353535353535880de0b6b3a76400008025a04f4c17305743700648bc4f6cd3038ec6f6af0df73e31757007b7f59df7bee88da07e1941b264348e80c78c4027afc65a87b0a5e43e86742b8ca0823584c6788fd0',
    tx: {
        nonce: '0x0',
        gasPrice: '0x4a817c800',
        gas: '0x5208',
        to: '0x3535353535353535353535353535353535353535',
        value: '0xde0b6b3a7640000',
        input: '0x',
        v: '0x25',
        r: '0x4f4c17305743700648bc4f6cd3038ec6f6af0df73e31757007b7f59df7bee88d',
        s: '0x7e1941b264348e80c78c4027afc65a87b0a5e43e86742b8ca0823584c6788fd0',
        hash: '0xda3be87732110de6c1354c83770aae630ede9ac308d9f7b399ecfba23d923384'
    }
}

sendTransaction

web3.eth.personal.sendTransaction(transactionOptions, password [, callback])

This method sends a transaction over the management API.

주석

Sending your account password over an unsecured HTTP RPC connection is highly unsecure.

Parameters

  1. Object - The transaction options
  2. String - The passphrase for the current account
  3. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise<string> - The transaction hash.

Example

web3.eth.sendTransaction({
    from: "0xEB014f8c8B418Db6b45774c326A0E64C78914dC0",
    gasPrice: "20000000000",
    gas: "21000",
    to: '0x3535353535353535353535353535353535353535',
    value: "1000000000000000000",
    data: ""
}, 'MyPassword!').then(console.log);
> '0xda3be87732110de6c1354c83770aae630ede9ac308d9f7b399ecfba23d923384'

unlockAccount

web3.eth.personal.unlockAccount(address, password, unlockDuraction [, callback])

Signs data using a specific account.

주석

Sending your account password over an unsecured HTTP RPC connection is highly unsecure.

Parameters

  1. address - String: The account address.
  2. password - String - The password of the account.
  3. unlockDuration - Number - The duration for the account to remain unlocked.

Example

web3.eth.personal.unlockAccount("0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", "test password!", 600)
.then(console.log('Account unlocked!'));
> "Account unlocked!"

lockAccount

web3.eth.personal.lockAccount(address [, callback])

Locks the given account.

주석

Sending your account password over an unsecured HTTP RPC connection is highly unsecure.

Parameters

1. address - String: The account address. 4. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise<boolean>

Example

web3.eth.personal.lockAccount("0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe")
.then(console.log('Account locked!'));
> "Account locked!"

getAccounts

web3.eth.personal.getAccounts([callback])

Returns a list of accounts the node controls by using the provider and calling the RPC method personal_listAccounts. Using web3.eth.accounts.create() will not add accounts into this list. For that use web3.eth.personal.newAccount().

The results are the same as web3.eth.getAccounts() except that calls the RPC method eth_accounts.

Returns

Promise<Array> - An array of addresses controlled by node.

Example

web3.eth.personal.getAccounts()
.then(console.log);
> ["0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", "0xDCc6960376d6C6dEa93647383FfB245CfCed97Cf"]

importRawKey

web3.eth.personal.importRawKey(privateKey, password)

Imports the given private key into the key store, encrypting it with the passphrase.

Returns the address of the new account.

주석

Sending your account password over an unsecured HTTP RPC connection is highly unsecure.

Parameters

  1. privateKey - String - An unencrypted private key (hex string).
  2. password - String - The password of the account.

Returns

Promise<string> - The address of the account.

Example

web3.eth.personal.importRawKey("cd3376bb711cb332ee3fb2ca04c6a8b9f70c316fcdf7a1f44ef4c7999483295e", "password1234")
.then(console.log);
> "0x8f337bf484b2fc75e4b0436645dcc226ee2ac531"